How to print map() object results stored in a variable multiple times?

Question:

Recently I was trying out something for ways to print a map() result, where I came across *

I tried out this:

>>> def inc(x):
...     return x+1
...
>>> a = map(inc,[1,2,3,4,5])
>>> print(*a)
2 3 4 5 6
>>> print(*a)

Here with a function inc() I stored the map object result in a. On printing it using print(*a),
I get the desired output. Running the command second time prints out nothing. Why?

I wondered that has anything happened to a, and tried this to check type() of a:

>>> type(a)
<class 'map'>

But it seems to be all good. So why am I not able to print results using print(*a) command a second time?
Even when I tried to print using [i for i in a], Its possible for the first time and not possible for the second, it gets me []. What is the problem?

Asked By: JenilDave

||

Answers:

map object can be considered as an iterator over a some sequence of data. In a nutshell, the map object applies the function that you have specified, each time next is applied to it. It does not store the result.

So, with *, you effectively apply next onto a until StopIteration, and this means that you effectively apply the inc function at your data.

After that, you should re-initialize the map. Alternatively, you could use tee.

https://docs.python.org/3/library/itertools.html#itertools.tee

If you want to store the result of map in a container, then you could initialize a list from the result of map, e.g.

l = list(map(inc, [1, 2, 3, 4]))

This is equivalent of calling *a, but the result is passed to the list constructor and then assigned to the variable l.

Answered By: Xxxo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.