indexed() generator

Michael Robin me at mikerobin.com
Wed Jan 23 14:01:36 EST 2002


mlh at vier.idi.ntnu.no (Magnus Lie Hetland) wrote in message news:<slrna4tk97.bh6.mlh at vier.idi.ntnu.no>...
> In article <mailman.1011750813.24541.python-list at python.org>, Delaney,
> Timothy wrote:
> 
> >A perhaps better method would be:
> >
> >def indexed (seq, start=0)
> >    i = start
> >    for obj in seq:
> >        yield i, obj
> >        i += 1
> >
> >(sometimes a non-zero start index is wanted).
> 
> Perhaps you should add a step while you're at it? And maybe even stop
> (in case you don't want the entire sequence)? Just keeping some
> similarity with range()...

...and unless I'm missing something, I assume that you want to start returning
objects at index 'start', not a 0. E.g.:

  def indexed (seq, start=0)
      i = start
      while i < len(seq):
          yield i, seq[i]
          i += 1

no?

mike



More information about the Python-list mailing list