Can you please help me on this issue?
a = [1, 2, 3, 4, 5, 6]
double = map(lambda x:x*2, a)
b = sum(double)
[2, 4, 6, 8, 10, 12]
I’ve learned before I have to use a list:
… in order to print a map result, but honestly I don’t know why…
And what about zero as an output when I run print (b)?
Thank you so much,
map() returns an iterator (see the documentation).
When you call
list(double) in the first
print() statement this iterator gets incremented and incremented until it reaches the end. Afterwards you can think of the iterator as “consumed”.
So when you use
double again, there are no more elements, so the
sum() adds up zero elements and returns
Try your snipped again, but this time without the first
print(). You will see the correct value.
To illustrate what @siebenschlaefer said,
>>> a = map(lambda x: x, [1, 2, 3])
This is a difference between an
Iterator and a
Not exactly. All sequences are iterable. It is a difference between an iterator and a sequence.
(Though, strictly speaking, a sequence can be an iterator too. I have never seen one.)
Thanks for the catch! My fingers sometimes type faster than my brain picks the correct word.