when I wrote map(sum,[1, 2]))
, I have not gotten any errors but as soon as you write list(map(sum,[1, 2])))
you will get an error. Actually, I know about the error "int is not an iterable" that you will get when you run this code.
But I just want to know why map(sum,[1, 2]))
not evaluate as like as list(map(sum,[1, 2])))
code.
Would you please help me out?

- 419
- 1
- 6
- 14
-
https://stackoverflow.com/questions/47927234/using-map-to-sum-the-elements-of-list Check for duplicated question before asking – Jules Civel Jul 07 '21 at 09:47
-
thanks for your comment! actually, I checked it before. but it did not help me why this happened exactly – Sara Jul 07 '21 at 09:47
-
2Does this answer your question? [Using map to sum the elements of list](https://stackoverflow.com/questions/47927234/using-map-to-sum-the-elements-of-list) – Jules Civel Jul 07 '21 at 09:48
-
No, it did not. In that post, just showed that this is happening and no explanation is given for exactly what happens when we get this answer. – Sara Jul 07 '21 at 09:52
-
1Thanks for pointing out that question. I edited my post to clarify more about what is my problem exactly. – Sara Jul 07 '21 at 09:58
-
I think your actual question is addressed by this: https://stackoverflow.com/questions/37417210/lazy-evaluation-of-map – pavon Jul 07 '21 at 22:48
-
Yeah, it is. Thnx:) – Sara Jul 08 '21 at 09:22
2 Answers
map
returns a lazy iterator. Any error that occurs when it tries to produce the next element will only appear once you start consuming the iterator. That is what list(map(...))
does.
For the error itself:
sum([1, 2]) # == 3
will work, but
map(sum, [1, 2])
will try to produce the values
sum(1) # this triggers the error
sum(2)
which does not work, as 1
and 2
are not iterables themselves.
You can retrace those two separate steps of creation of the lazy iterator object and its consumption:
m = map(sum, [1, 2])
# is ok: first arg a func, second arg an iterable, the constructor of the Map class is still a happy camper!
s = next(m)
# not ok: pulling the first element from the iterator
# calls sum(1) and fails expectedly.
# Repeated calls to `next` are what happens under the hood in the
# list constructor

- 72,016
- 6
- 67
- 89
You've written it in a way that map
applies function sum
to every element separately, i.e. it would try to call sum(1)
and then sum(2)
, which can't be done, because neither 1
or 2
are iterable (they're not list/set/string etc).
Why didn't it throw an error with just map(sum,[1, 2]))
? Because calling map
doesn't actually start to do any actions, instead it creates a so called lazy iterator, that will start applying actions only when you ask for it (e.g. calling list(map(sum,[1, 2])))
asks for iterator to process all the elements, and it starts throwing errors because of what I already said.

- 6,555
- 1
- 18
- 37