PEP 276 Simple Iterator for ints (fwd)

David Eppstein eppstein at ics.uci.edu
Wed Nov 14 19:46:37 EST 2001


In article <7xadxo27tr.fsf at ruckus.brouhaha.com>,
 Paul Rubin <phr-n2001d at nightsong.com> wrote:

> > >     for i in 0 .. len(sequence)-1:
> > 
> > This is very common in C, but is it so common in Python?
> > Isn't it usually more idiomatic to do
> >     for item in sequence
> > ?
> 
> Sometimes you want to use the index in the loop.  Maybe the loop syntax
> should be extended somehow to easily let you do that.

Ok, suppose you are numbering output lines, or something.
You may likely want to number them starting from one, anyway.

index = 1
for item in sequence:
    print index, item
    index = index+1

would be my preference over

for i in range(len(sequence)):
    print i+1, sequence[i]

for three reasons:
1. it works with iterators as well as lists
2. you can skip items in the sequence and keep the numbering contiguous
3. I don't trust sequence[i] to take constant time
4. I'm not as likely to produce an off-by-one error
5. I don't like having to remember what range(n) means

...among our *many* reasons are...
-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list