Python enumerate() Function
Description
The enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, listing both the data and the data subscripts. It is generally used in for loops.
Available in Python 2.3 and above; the start parameter was added in Python 2.6.
Syntax
The following is the syntax of the enumerate() method:
enumerate(sequence, [start=0])
Parameters
- sequence -- A sequence, iterator, or other object that supports iteration.
- start -- The value of the starting position of the subscript.
Return Value
Returns an enumerate object.
Examples
The following shows examples of using the enumerate() method:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # The subscript starts from 1
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # The subscript starts from 1
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Regular for loop
>>> i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
... print i, seq[i]
... i += 1
...
0 one
1 two
2 three
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
... print i, seq[i]
... i += 1
...
0 one
1 two
2 three
for loop using enumerate
>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
Python Built-in Functions