Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - same instruction, different outcome

Could someone help me understand what is going on in the following Python code (python 3.2)? I'm really clueless here.

import sys
u = sys.stdin.readline()
   # try entering the string "1 2 3" 
r = map(lambda t: int(t.strip()),u.split())
print(sum(r)) # prints 6
print(sum(r)) # prints 0 ?

Thank you.

like image 785
Lambda Mu Avatar asked Jul 15 '11 18:07

Lambda Mu


1 Answers

map() in Python 3.x returns an iterator, not a list. Putting it through sum() the first time consumes it, leaving nothing for the second time.

like image 170
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 01:09

Ignacio Vazquez-Abrams