Skipping Parts of a For Loop

Alex Martelli aleax at aleax.it
Sat Sep 14 21:51:46 CEST 2002


Thomas Guettler wrote:

> Hi!
> 
> Is there a way to skip some parts in a for loop?
> 
> 
> for i in range(3):
> print "i before", i
> i=2
> print "i after", i
> 
> #Results in:
> 
> i before 0
> i after 2
> i before 1
> i after 2
> i before 2
> i after 2
> 
> Is there a way to skip some parts?
> 
> "continue" skipps one element. But how can
> I skip several?

In Python 2.2, a for loop like:
    for x in something:
        "any statements here"
is equivalent to:
    _aux = iter.something()
    while True:
        try: x = _aux.next()
        except StopIteration: break
        "any statements here"

You can take advantage of this as long as you
bind the iterator to a name, exploiting also the fact
that iter(iter(x)) is iter(x) [i.e., iter is idempotent
on iterators]:

aux = iter(range(3))
for i in aux:
  print "i before", i
  for i in range(i,3): aux.next()
  print "i after", i

Each calls to the next method of the iterator object
"skips" a whole coming leg of the for loop.


Alex




More information about the Python-list mailing list