Why I'm getting empty list after using zip in python?

Question:

After I zip two lists and print the zip object as a list, I get the desired output. But when I wanted to make another list from the zip object I get an empty list. Why this is happening?

Code:

result = zip(number_list, str_list)

# Converting iterator to list
result_list = list(result)
result_list2 = list(result)


print(result_list)
print(result_list2)

Output:

[(1, 'one'), (2, 'two'), (3, 'three')]
[]

Answers:

zip returns an iterator object. The first time you convert it to a list, the iterator is consumed, and after that point it’s empty. You’ll get the behavior you expect if you convert it to a list immediately and then copy it:

result = list(zip(number_list, str_list))

# Converting list to more lists
result_list = result.copy()
result_list2 = result.copy()

In general, a zip object is meant to be used immediately (e.g. within a for loop or passed directly to a function that takes an iterable). Assigning the result of calling zip to a variable is not going to be useful in very many cases.

Answered By: Samwise

Because zip returns an iterator, and an iterator is meant to be iterated only once.

The first time you create the list out of the zip object by this:

>>> result_list = list(result)

The items in result get iterated and a list is created out of it.

And the next time you try to create list out of the same zip object, the items already have been iterated and it doesn’t iterate any further that is why you get an empty list.

>>> result_list2 = list(result)

You can try passing the result to next, and you will get StopIterationError which means the iterator can no longer be iterated any further:

>>> next(result)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration
Answered By: ThePyGuy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.