Why garbage collection act weird this in Jupyter Notebook?

Question:

why second loop don’t print any thing?!

z_rng = zip(range(10), range(10))

# this loop is run and print
for i,j in z_rng:
    print(i,j)

# this loop is not run and don't print anything
for l, k in z_rng:
    print(l, k)

Or when print as list again loop don’t run.

z_rng = zip(range(10), range(10))

# this loop is run and print
print(list(z_rng))

# this loop is not run and don't print anything
for l, k in z_rng:
    print(l, k)
Asked By: RanN

||

Answers:

Iterators can only be iterated once because they generate the values on the fly (they are not stored inside the iterator). The garbage collector isn’t the cause. You can create two iterators assigning two variables in one line.

You can check this question for further information.

Answered By: Fran Arenas