Performing len on list of a zip object clears zip [duplicate]

In Python 3 zip is a generator. The generator is being exhausted when you do list(z). You can create a list from the values returned by the generator and operate on that.

l = list(z)
len(l)
# -> 3
l
# -> [(1, 'a', 11), (2, 'b', 22), (3, 'c', 33)]

Generators are a good thing. They allow us to write memory-efficient code in nearly the same way we would write code that deals with lists. To use an example from the linked wiki:

def double(L):
    return [x*2 for x in L]

Could be rewritten as a generator to avoid creating another list in memory:

def double(L):
    for x in L:
        yield x*2

Leave a Comment