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?
-
stackoverflow.com/questions/47927234/… Check for duplicated question before askingJules Civel– Jules Civel2021-07-07 09:47:09 +00:00Commented Jul 7, 2021 at 9:47
-
thanks for your comment! actually, I checked it before. but it did not help me why this happened exactlySara– Sara2021-07-07 09:47:59 +00:00Commented Jul 7, 2021 at 9:47
-
2Does this answer your question? Using map to sum the elements of listJules Civel– Jules Civel2021-07-07 09:48:33 +00:00Commented Jul 7, 2021 at 9: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– Sara2021-07-07 09:52:01 +00:00Commented Jul 7, 2021 at 9:52
-
1Thanks for pointing out that question. I edited my post to clarify more about what is my problem exactly.Sara– Sara2021-07-07 09:58:35 +00:00Commented Jul 7, 2021 at 9:58
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
Comments
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.