indexed() generator

Alex Martelli aleax at aleax.it
Fri Jan 25 10:21:14 EST 2002


"Michael Chermside" <mcherm at destiny.com> wrote in message
news:mailman.1011968940.24241.python-list at python.org...
    ...
>   * The following approach is simpler and cleaner _IF_ the reader is
>     familiar with the convention:
>
>      # Approach 3:
>      for i, item in indexed(list):
>          <code with i and item>
    ...
> So... anyone else agree?

Yes.  See also:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52233

where I offer two implementations of indexed (spelled Indexed)
for Python 2.1 (with 'list' having to be a sequence, of course,
since iterators were not around yet):

class Indexed:
    def __init__(self, seq):
        self.seq = seq
    def __getitem__(self, i):
        return self.seq[i], i


or


import sys
_indices = xrange(sys.maxint)

def Indexed(sequence):
    return zip(sequence, _indices)


both meant to be used as in your example.  In Python 2.2,
defining indexed as an iterator seems most natural:

class indexed:
    def __init__(self, seq):
        self.iter = iter(seq)
        self.i = -1
    def next(self):
        self.i += 1
        return self.i, self.iter.next()


or of course, as multiply suggested in this thread,


from __future__ import generators

def indexed(seq):
    seq = iter(seq)
    i = 0
    for item in seq:
        yield i, item
        i += 1


Alex






More information about the Python-list mailing list