Reputation: 124
Given the following:
(I) a = map(function, sequence)
(II) a = [function(x) for x in sequence]
When would I need to use (I)? Why choose a map object over a list when the latter is subscriptable and IMO more readable?
Also, could someone explain line 6 of the following code (Python 3):
>>>import math
>>>a = map(int,str(math.factorial(100)))
>>>sum(a)
648
>>>sum(a)
0
Why is the sum of the map object changing?
Upvotes: 1
Views: 80
Reputation: 123400
When would I need to use (I)? Why choose a map object over a list when the latter is subscriptable and IMO more readable?
map
was introduced in Python 1.0, while list comprehension was not introduced until Python 2.0.
For Python 2+, you never need to use one or the other.
Reasons for still using map
could include:
map
is very common across languages. If Python's not your native language, "map" is the function you'll look up. map
is often shorter. Compare map
and lambda f,l: [f(x) for x in l]
.Upvotes: 2
Reputation: 19264
From the docs:
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel...
The sum
changes to 0 because the iterator is iterated, so it becomes nothing. This is the same concept with .read()
(Try calling x = open('myfile.txt')
, and then type print x.read()
twice.)
In order to preserve the iterable, surround it with list()
:
>>> import math
>>> a = map(int,str(math.factorial(100)))
>>> sum(a)
648
>>> sum(a)
0
>>> a = list(map(int,str(math.factorial(100))))
>>> sum(a)
648
>>> sum(a)
648
Example from the docs:
>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
Upvotes: 1
Reputation: 15160
I is an iterator -- it creates a stream of values which then vanish. II is a list -- it lasts for a while and has lots of features, like len(mylist)
and mylist[-3:]
.
The sum
changes because the iterator vanishes after you use it.
Use lists and list comprehensions. If you process tons of data, then iterators (and generators, and generator comprehensions) are awesome, but they can be confusing.
Or, use an iterator and convert into a list for further processing:
a = list( map(int,str(math.factorial(100))) )
Upvotes: 2