Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 7 lines
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).

2 comments

Raymond Hettinger 19 years, 2 months ago  # | flag

Shorter and faster with improved parameter name. How about:

__builtin__.enumerate = lambda seq:  zip(xrange(len(seq)), seq)

BTW, the "iterable" argument should be named "sequence" because the recipe only works with arguments supporting __len__().

Steven Bethard 19 years, 2 months ago  # | flag

using a class. If you want to make enumerate an iterator like it is in Python 2.3, you could use a class:

py> class enumerate:
...     def __init__(self, seq):
...         self.seq = seq
...     def __getitem__(self, i):
...         return i, self.seq[i]
...
py> enumerate([5, 7])
<__main__.enumerate instance at 0x0114D4E0>
py> list(enumerate(xrange(4)))
[(0, 0), (1, 1), (2, 2), (3, 3)]
py> list(enumerate('abcde'))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

Note that I used the old sequence protocol to be "really" backwards compatible - __iter__, etc. was only introduced in 2.2 IIRC.

Created by Nitesh Patel on Thu, 27 Jan 2005 (PSF)
Python recipes (4591)
Nitesh Patel's recipes (1)

Required Modules

Other Information and Tasks