1

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?

7
  • stackoverflow.com/questions/47927234/… Check for duplicated question before asking Commented Jul 7, 2021 at 9:47
  • thanks for your comment! actually, I checked it before. but it did not help me why this happened exactly Commented Jul 7, 2021 at 9:47
  • 2
    Does this answer your question? Using map to sum the elements of list Commented 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. Commented Jul 7, 2021 at 9:52
  • 1
    Thanks for pointing out that question. I edited my post to clarify more about what is my problem exactly. Commented Jul 7, 2021 at 9:58

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.