simulate enumerate in python 2.1

John Machin sjmachin at lexicon.net
Mon Jul 10 18:46:05 EDT 2006


On 11/07/2006 2:30 AM, eight02645999 at yahoo.com wrote:
> hi,
> i am using python 2.1. Can i use the code below to simulate the
> enumerate() function in 2.3?

I'm bemused, boggled and bamboozled -- and that's just *one* letter of 
the alphabet ...

You are using Python 2.1, and you felt it necessary to ask on the 
newsgroup if it could be done instead of trying it out??? You would have 
found out after typing only one line that you were barking up the wrong 
  tree:

Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
 >>> from __future__ import generators
   File "<stdin>", line 1
SyntaxError: future feature generators is not defined

> If not, how to simulate in 2.1?
> thanks
> 
> from __future__ import generators
> def enumerate(sequence):
>     index = 0
>     for item in sequence:
>         yield index, item
>         index += 1
> 

Something like this:

 >>> class enumerate:
...     def __init__(self, seq):
...         self.seq = seq
...     def __getitem__(self, inx):
...         return inx, self.seq[inx]
...
 >>> alist = [9,8,7]
 >>> for i, item in enumerate(alist):
...    print i, item
...
0 9
1 8
2 7
# lookin' good
 >>> list(enumerate('qwerty'))
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
AttributeError: enumerate instance has no attribute '__len__'
# uh-oh
 >>> def patchit(self):
...     return len(self.seq)
...
 >>> enumerate.__len__ = patchit
 >>> list(enumerate('qwerty'))
[(0, 'q'), (1, 'w'), (2, 'e'), (3, 'r'), (4, 't'), (5, 'y')]
# lookin' better

There may be other details needed to complete the fake-up job, ... over 
to you.

HTH,
John



More information about the Python-list mailing list