Could you please explain this MAP issues?

Dear friends,

Can you please help me on this issue?

a = [1, 2, 3, 4, 5, 6]

double = map(lambda x:x*2, a)
print(list(double))

b = sum(double)
print(b)

Result:

[2, 4, 6, 8, 10, 12]
0

I’ve learned before I have to use a list:

“print(list(double))”

… 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,

Rod.

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 0.

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])
>>> next(a)
1
>>> next(a)
2
>>> list(a)
[3]
>>> list(a)
[]

This is a difference between an Iterable Iterator and a Sequence.

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.

Thanks, @siebenschlaefer and @IsaacG !