Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List returned by map function disappears after one use

Tags:

I'm new to Python. I'm using Python 3.3.2 and I'm having a hard time figuring out why the following code gives me an error:

strList = ['1','2','3'] intList = map(int,strList) largest = max(intList) smallest = min(intList) 
Traceback (most recent call last):   File "<stdin>", line 1, in <module> ValueError: min() arg is an empty sequence 

However this code gives me no errors at all:

strList = ['1','2','3'] intList = list(map(int,strList)) largest = max(intList) smallest = min(intList) 

My thought is that when intList is assigned to the return value of the map function, it becomes an iterator rather than a list, as per the docs. And perhaps as a side effect of calling max(), the iterator has been iterated to the end of the list, causing Python to believe the list is empty. (I'm drawing from C knowledge here. I'm not familiar with how iterators truly work in Python.) The only evidence I have to support this is that, for the first block of code:

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

whereas for the second block of code:

>>> type(intList) <class 'list'> 

Can someone confirm or deny this for me please?

like image 415
Dizzyspiral Avatar asked Feb 11 '14 23:02

Dizzyspiral


People also ask

Does map return a list?

NOTE : You can pass one or more iterable to the map() function. Returns : Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Does map return a generator?

Using Generator Expressions map() returns a map object, which is an iterator that yields items on demand. So, the natural replacement for map() is a generator expression because generator expressions return generator objects, which are also iterators that yield items on demand.


2 Answers

You are exactly correct. In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise StopIteration immediately, as though it were empty. max consumes the whole thing, and min sees the iterator as empty. If you need to use the elements more than once, you need to call list to get a list instead of an iterator.

like image 129
user2357112 supports Monica Avatar answered Nov 02 '22 23:11

user2357112 supports Monica


from your map documentation:

Return an iterator that applies function to every item of iterable, yielding the results.

and from http://docs.python.org/3/library/stdtypes.html#typeiter

Once an iterator’s next() method raises StopIteration, it must continue to do so on subsequent calls.

So an iterator, regardless of the underlying data object, can only be used once. It builds on the concept of a generator.

itertools.tee can be used make multiple independent iterators from one.

l1,l2 = itertools.tee(intList,2) max(l1) min(l2) 
like image 21
hpaulj Avatar answered Nov 02 '22 23:11

hpaulj