Total noob question here but I really want to know the answer.
I have no idea why the zip object simply "disappears" after I attempt to iterate through it in its list form: eg.
>>> A=[1,2,3]
>>> B=['A','B','C']
>>> Z=zip(A,B)
>>> list(Z)
>>> [('C', 3), ('B', 2), ('A', 1)]
>>> {p:q for (p,q) in Z}
{1: 'A', 2: 'B', 3: 'C'}
>>> {p:q for (p,q) in list(Z)}
{}
>>> list(Z)
[]
(this is in Python 3.4.2)
Can anybody help?
There was a change of behavior between Python2 to Python3:
in python2, zip returns a list of tuples while in python3 it returns an iterator.
The nature of iterator is that once it's done iterating the data - it points to an empty collection and that's the behavior you're experiencing.
Python2:
Python3:
zip
creates an object for iterating once over the results. This also means it's exhausted after one iteration:You need to call
zip(a,b)
every time you wish to use it or store thelist(zip(a,b))
result and use that repeatedly instead.