simulate enumerate in python 2.1

E

eight02645999

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
 
T

Terry Reedy

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
 
J

John Machin

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.
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:
.... 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' goodTraceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: enumerate instance has no attribute '__len__'
# uh-oh.... return len(self.seq)
....[(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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top