Python: Understanding the implications of iterating through a zip object [duplicate]
This problem will not be created by list(aabb)
but with list(ab)
in your code right now:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
ab = zip(a, b)
aabb = list(ab)
print(list(ab)) # -> []
The problem is that zip
is an iterator which stores values once and are then disposed like so:
ab = zip(a, b) # iterator created
aabb = list(ab) # elements read from ab, disposed, placed in a list
print(list(ab)) # now ab has nothing because it was exhausted
This on the other hand should work because aabb
is just a list, not the exhausted iterator ab
:
ab = zip(a, b)
aabb = list(ab)
print(list(aabb)) # -> [(1, 5), (2, 6), (3, 7), (4, 8)]