Looping over lists

Alex Martelli aleax at mac.com
Sat May 5 10:58:13 EDT 2007


Dustan <DustanGroups at gmail.com> wrote:

> On May 5, 3:15 am, kaens <apatheticagnos... at gmail.com> wrote:
> > I think the for i in range() is more readable (Maybe because I'm
> > coming from a c-style syntax language background) -  but what would
> > the benefits of using enumerate be (other that being more . . .
> > pythonesque?)
> 
> It doesn't create a whole new list just for iterating.

As the example list was of length 5, that's not all that important in
this case.  In cases where it _is_ crucial, you can use xrange.

The performance of the various ways of looping is substantially the
same:

$ python -mtimeit -s'n=5; a=n*[23]' 'for i in range(n): x=a[i]'
1000000 loops, best of 3: 1.4 usec per loop
$ python -mtimeit -s'n=5; a=n*[23]' 'for i in xrange(n): x=a[i]'
1000000 loops, best of 3: 1.18 usec per loop
$ python -mtimeit -s'n=5; a=n*[23]' 'for i,v in enumerate(a): x=v'
1000000 loops, best of 3: 1.49 usec per loop
$ 

Here, xrange is minutely faster and enumerate slower, but each speed
difference "in the noise".  Focusing on clarity is thus well warranted.

> > > > for i in range(n):
> > > >     for j in range(i+1, n):
> > > >         print a[i], a[j]
> >
> > >         Ah, but wouldn't the cleaner Python be something like
> >
> > > >>> a = [1, 2, 3, 4, 5, 3, 6]   #just to confuse matters
> > > >>> for pos, val in enumerate(a):
> > > ...     for v2 in a[pos+1:]:
> > > ...             print val, v2

This "breaks symmetry", by using enumerate in the outer loop and a slice
in the inner loop; the symmetrical construction of using range in both
loops is a big conceptual/clarity win -- the reader of the code needs to
"grasp" one fewer concept (locally).  Using xrange in both loops would
be just as good from this POV.


Alex



More information about the Python-list mailing list