Skip to content
Advertisement

python – different behavior of print(*generator, )

Question

Please help understand why the two cases act differently although both use a generator (i for i in range(5)).

JavaScript
JavaScript

Advertisement

Answer

When you use the * operator on a generator expression (or any iterator for that matter), it consumes it:

JavaScript

You’d need to recreate it to re-use it, which is what you’re doing in your first example:

JavaScript

Note on range

Since I’ve used range for this example, it’s important to note that range doesn’t share this behavior, but an iterator over range does:

JavaScript

More detail can be found in this answer

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement