Vorac
Vorac

Reputation: 9114

How to walk an iterator by list comprehension

>>> a = [1,2,3,4,5,6]
>>> b = ["q","r","f","v","d","a"]
>>> c = zip(a,b)
>>> list(c)
[(1, 'q'), (2, 'r'), (3, 'f'), (4, 'v'), (5, 'd'), (6, 'a')]
>>> [x for x in list(c)]
[]

Why does the comprehension not work? I want to do some computations with the elements and store them in a new list.

Upvotes: 0

Views: 665

Answers (1)

Daniel Lenz
Daniel Lenz

Reputation: 3857

zip() creates an iterator that can only be used once.

If you use it to construct the list(c), there are no more items in the iterator that could be used for the list comprehension.

If you skip the call to list(c), your list comprehension works perfectly fine.

You can also see that by looking at the individual steps of the iterator:

In [60]: c = zip(a, b)

In [61]: c.__next__()
Out[61]: (1, 'q')

In [62]: c.__next__()
Out[62]: (2, 'r')

In [63]: c.__next__()
Out[63]: (3, 'f')

In [64]: c.__next__()
Out[64]: (4, 'v')

In [65]: c.__next__()
Out[65]: (5, 'd')

In [66]: c.__next__()
Out[66]: (6, 'a')

In [67]: c.__next__()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-67-bc609abc99c4> in <module>()
----> 1 c.__next__()

StopIteration:

If you use the list comprehension right away, you get the desired result:

In [68]: c = zip(a, b)

In [69]: mylist = [x for x in list(c)]

In [70]: mylist
Out[70]: [(1, 'q'), (2, 'r'), (3, 'f'), (4, 'v'), (5, 'd'), (6, 'a')]

Upvotes: 4

Related Questions