indexed looping, functional replacement?

Raymond Hettinger python at rcn.com
Sat Nov 9 20:34:58 EST 2002


> > I would like a simpler approach to avoid having to manually maintain
> > an index, maybe functional if possible.
>
> In Python 2.3, the enumerate built-in will do just that:
>
> [alex at lancelot alf]$ python2.3
> Python 2.3a0 (#4, Nov  6 2002, 09:18:17)
> [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> for x in enumerate('ciao'): print x
> ...
> (0, 'c')
> (1, 'i')
> (2, 'a')
> (3, 'o')
> >>>

In Python 2.2.2, you can roll your own enumerate:

>>> from __future__ import generators
>>> def enumerate(seq):
    i = 0
    for elem in seq:
        yield (i, elem)
        i += 1

>>> list(enumerate('later dude'))
[(0, 'l'), (1, 'a'), (2, 't'), (3, 'e'), (4, 'r'), (5, ' '), (6, 'd'), (7,
'u'), (8, 'd'), (9, 'e')]


Raymond Hettinger





More information about the Python-list mailing list