Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python
Early halt for iterating a_list and iter(a_list)
 

Index | Next | Previous | View Flat


Lie.1296 at gmail

Aug 15, 2008, 7:36 AM


Views: 95
Permalink
Early halt for iterating a_list and iter(a_list)

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)], [], [], [], []], [[],
[], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [],
[], [], []], [[], [], [], [], []]]
--
http://mail.python.org/mailman/listinfo/python-list

Subject User Time
Early halt for iterating a_list and iter(a_list) Lie.1296 at gmail Aug 15, 2008, 7:36 AM
    Re: Early halt for iterating a_list and iter(a_list) fredrik at pythonware Aug 15, 2008, 7:55 AM
    Re: Early halt for iterating a_list and iter(a_list) Lie.1296 at gmail Aug 22, 2008, 7:23 AM
    Re: Early halt for iterating a_list and iter(a_list) steve at REMOVE-THIS-cybersource Aug 22, 2008, 6:36 PM

  Index | Next | Previous | View Flat
 
 


Interested in having your list archived? Contact lists@gossamer-threads.com
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.