By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,537 Members | 1,440 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,537 IT Pros & Developers. It's quick & easy.

simulate enumerate in python 2.1

P: n/a
hi,
i am using python 2.1. Can i use the code below to simulate the
enumerate() function in 2.3? 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

Jul 10 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a

<ei***********@yahoo.comwrote in message
news:11**********************@m79g2000cwm.googlegr oups.com...
hi,
i am using python 2.1. Can i use the code below to simulate the
enumerate() function in 2.3? 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
Didn't generators and the new iterator protocol arrived in 2.2?
If so you have to write an iterator in the older __getitem__ protocol,
which should be in the 2.1 docs.

tjr

Jul 10 '06 #2

P: n/a
On 11/07/2006 2:30 AM, ei***********@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
Jul 10 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.