Python 2.3+ "enumerate" function is pretty handy. This bit of code should allow you to use it transparently in pre-Python 2.3 systems.
1 2 3 4 5 6 7 | # Check if the function already exists first
try:
enumerate
except:
# Allow access like a builtin function
import __builtin__
__builtin__.enumerate = lambda seq: zip(xrange(len(seq)), seq)
|
Some systems out there are still using Python 2.2 or previous versions. The "enumerate" function is Python 2.3 is pretty handy. Using this piece of code should let you use the builtin "enumerate" function just as you would in Python 2.3+.
I would appreciate comments and improvements.
- Updated after the comment from Raymond (many thanks).
Shorter and faster with improved parameter name. How about:
BTW, the "iterable" argument should be named "sequence" because the recipe only works with arguments supporting __len__().
using a class. If you want to make enumerate an iterator like it is in Python 2.3, you could use a class:
Note that I used the old sequence protocol to be "really" backwards compatible - __iter__, etc. was only introduced in 2.2 IIRC.