Martin McBride
Dec 24, 2023

In your squares example, there are a couple of important differences between a list and a generator expression. The generator expression returns an iterator, which doesn't behave exactly like a list.

First is that you can index a list, eg squares[2]. You can't do that with a generator expression.

The second is that the an iterator can only be used once. If you pass an iterator into func_a() that accesses its elements, then into func_b() that tries to do the same, the second function will fail because the iterator has already been exhausted.

Do that with a list and it will be fine.

Generator expressions are very useful, but it is important to understand their limitations. They are not a drop in replacement for list comprehensions in all circumstances.

Martin McBride
Martin McBride

No responses yet