Rodrigo Girão Serrão 🐍🚀 @mathspp.com · Jan 19

Let me teach you to break a Python law. Iterators can only be traversed once: ```py squares = (x ** 2 for x in range(3)) for sq in squares: print(sq, end=", ") # 0, 1, 4, for sq in squares: print(sq, end=", ") # <no output> ``` The second loop produces no output!

4 likes 1 replies

?

Replies

Rodrigo Girão Serrão 🐍🚀 · Jan 19

That's because the generator was exhausted during the first loop. But you can work around this limitation: `itertools.tee` allows you to create 2+ independent iterators out of a single iterator: 👇