In the exemple is used “list(double_list)” to print the list, but why? double_list alone is not a list?
I tried to use “print(double_list)” and I know it doesn’t work, I got a weird number, but why is it? And that number, is it the ID?
One more question, when I try to use just “list” instead of “list_1”, I got an error “something is not defined”, why that happens? Do I need to always use a underscore?
num_list = [0, 1, 2, 3, 4, 5]
double_list = map(lambda n: n * 2, num_list)
print(list(double_list))
thanks
Course: Educative: Interactive Courses for Software Developers
Lesson: https://www.educative.io/courses/learn-python-3-from-scratch/mELQq49yJ2n
Course: https://www.educative.io/courses/learn-python-3-from-scratch
Lesson: https://www.educative.io/courses/learn-python-3-from-scratch/mELQq49yJ2n
Hi @Lugumedeiros !!
In the given example,
num_list = [0, 1, 2, 3, 4, 5]
double_list = map(lambda n: n * 2, num_list)
print(list(double_list)) # Convert the iterator to a list and then print it
We have a list num_list
containing some numbers, and we’re using the map
function with a lambda function to double each element in num_list
. The result of the map
operation is an iterator, not a list. That’s why we need to use list(double_list)
to convert the iterator back into a list before printing.
Let’s break down your questions:
-
Using list(double_list)
instead of just double_list
The map
function returns an iterator in Python. An iterator is a type of object that produces values one at a time as you iterate over it. It doesn’t generate all the values at once, which can be memory-efficient. In order to see the actual values produced by the map
operation, you need to convert the iterator into a list. The list()
function is used to consume the iterator and create a list from its values. So, list(double_list)
is used to convert the iterator double_list
into a list and then print it.
-
print(double_list)
not working and produce a weird number
When you directly try to print the double_list
iterator, Python displays its memory address, which is represented as a weird number. This is not the intended behavior because you’re seeing the internal representation of the iterator, not the actual values it produces.
-
Encountering error when using just list
instead of list(double_list)
In this code, we are using the map
function to create an iterator double_list
. When we use the function list
(like list(double_list)
), we are converting this iterator into a list. If you try to use list
without parentheses like list
, Python interprets it as you trying to access a variable named list
, which is not defined in your code. Adding an underscore or another identifier after list
prevents this confusion and ensures you’re calling the built-in list()
function.
I hope it helps. Happy Learning
1 Like