# Early halt for iterating a_list and iter(a_list)

Lie Lie.1296 at gmail.com
Fri Aug 15 16:36:54 CEST 2008

```When you've got a nested loop a StopIteration in the Inner Loop would
break the loop for the outer loop too:

a, b, c = [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]

def looper(a, b, c):
for a_ in a:
for b_ in b:
for c_ in c:
print a_, b_, c_

looper(a, b, c)  # Intended behavior [1]
a, b, c = iter(a), b, iter(c)  # b is intentionally not iter()-ed
looper(a, b, c)  # Inner StopIteration prematurely halt outer loop [2]

[1]
1 1 1
1 1 2
... a very long result ...
3 4 4
3 4 5

[2]
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5

Why is this behavior? Or is it a bug?

This is a potential problem since it is possible that a function that
takes an iterable and utilizes multi-level looping could be
prematurely halted and possibly left in intermediate state just by
passing an iterator.

A similar behavior also exist in list comprehension.
>>> a, b, c = [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]
>>> [[[(a_, b_, c_) for a_ in a] for b_ in b] for c_ in c]
[[[(1, 1, 1), (2, 1, 1),  ... result snipped ... , (3, 5, 6), (4, 5,
6)]]]

>>> a, b, c = [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]
>>> a, b, c = iter(a), b, iter(c)
>>> [[[(a_, b_, c_) for a_ in a] for b_ in b] for c_ in c]
[[[(1, 1, 1), (2, 1, 1), (3, 1, 1), (4, 1, 1)], [], [], [], []], [[],
[], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [],
[], [], []], [[], [], [], [], []]]

```