indexed() generator

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Fri Jan 25 23:21:46 CET 2002


On Fri, 25 Jan 2002 16:21:14 +0100, Alex Martelli <aleax at aleax.it> wrote:
>"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
...

Also note that mxTools has indices(x) which is like tuple(range(len(x)) and
irange(x) which is like tuple(zip(indices(x), x)).  Of course now that we have
generators they could use those, but I like the mxTools functions and think
they'd be just fine except for huge sequences in low memory situations.

There's lots of useful general-purpsoe utilities in mxTools.  Things like
NotGiven are handy for:

def f(x=NotGiven):
    if x is NotGiven: # None is a valid value
        ...

Not that votes count for much, but if people want Indexed functionality in the
core, I vote for the mxTools functions over the 'indexed' keyword.



More information about the Python-list mailing list