indexed() generator

Delaney, Timothy tdelaney at avaya.com
Wed Jan 23 18:21:47 EST 2002


> From: me at mikerobin.com [mailto:me at mikerobin.com]
> 
> 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()...

I thought about this, and the similarity to range(), but decided against it.
I was thinking more of the idiom:

for i, value in indexed(seq)
    i += 5
    print i, value

which is a not unusual occurrance. Howevr, it's probably too unusual to be
included in a standard implementation, now I think about it further.

> ...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

That was definitely not the idea - "start" is probably the wrong name for
the parameter - perhaps "addOffset"? In any case, the above would not work
with any iterator - only a true sequence.

Tim Delaney




More information about the Python-list mailing list