synchronized enumerate

Antoon Pardon apardon at forel.vub.ac.be
Tue Dec 20 04:03:00 EST 2005


Op 2005-12-20, smichr at gmail.com schreef <smichr at gmail.com>:

> What I would like to see supported is
> the concept that enumerate should give indices and items from an
> iterable--it does right now--but it should also allow you to access a
> different portion of the original list and *still* give the indices of
> that slice.  What I propose is an optional slice argument that would be
> used to return the sliced indices and items:
>
> def enum(l, slc=None):
>     if slc==None: #the usual ennumerate
>         for i, dat in enumerate(l):
>             yield i, dat
>     else:
>         if type(slc)<>slice:
>             raise TypeError, "slc must be a valid slice"
>         start, step = slc.start, slc.step
>         #
>         # we need actual values for start and step, so check for None
>         # and supply defaults
>         #
>         if step==None:step=1
>         if start==None:
>             if step>0:
>                 start=0
>             else:
>                 start=-1
>         for i, dat in enumerate(l[slc]):
>             j = i*step+start
>             if j<0: j+=len(l) #always give positive indices
>             yield j, dat
> ###
>>>> for i, x in enum(range(10), slice(start, start+count)):

The trouble with your suggestion (and the original enumerate,
which you rely on if no slice is provided) is that it doesn't
work as desired if you just give it a sequence that starts
at an other index than zero.

I have a table modules, tables are similar to lists but they
can start at arbitrary indexes. So if I have a table that
goes from -4 to +4, I would like enumerate(tab) or enum(tab)
to give me:

  (-4, tab[-4])
  (-3, tab[-3])

...

Of course this needs some cooperation from the sequence type.
Personnaly I would have though of a range method on the sequence
which could be used by enumerate to know where to start and end.

I also would prefer the possibilty to use the same notation
as with sequence subscription instead of having to use the
cumbersome slice notation. Something like:

  enum(lst, start:start+count)

Instead of

  enum(lst, slice(start, start+count))


Of course if you wouldn't mind brackets instead of parenthesis
we could implement enum as a vitual slice, we then would have
to write:

  enum[lst, start:start+count]


Just my 2 cents.

-- 
Antoon Pardon



More information about the Python-list mailing list