Alternative to standard C "for"

James Stroud jstroud at mbi.ucla.edu
Thu Feb 17 13:22:01 EST 2005


On Sat, 2005-02-05 at 10:49, BJörn Lindqvist wrote:
> > I am quite new to Python, and have a straight & simple question.
> > In C, there is for (init; cond; advance). We all know that.
> > In Python there are two ways to loop over i=A..B (numerical.):
> > 1) i = A
> >    while i<B:
> >       ...do something...
> >       i+=STEP
> 
> This is indeed quite ugly. You rarely need such loops in Python and
> with some thinking you can often translate the C-equivalent to
> something more pythonic. As you guessed, your second problem is best
> solved with a generator function - xrange(). It is completely equal to
> range() except that it returns a generator instead of a list.

It seems I need constructs like this all of the time

i = 0
while i < len(somelist):
  if oughta_pop_it(somelist[i]):
    somelist.pop(i)
  else:
    i += 1

There has to be a better way...

Any thoughts?

James

-----------------
7. Obsession with National Security
Fear is used as a motivational tool by the government over the masses.




More information about the Python-list mailing list