Python enumerate() Function
Description
The enumerate() function is used to combine an iterable data object (such as a list, tuple, or string) into an indexed sequence, listing both the data and its index at the same time; it is generally used in for loops.
Available in Python 2.3 and above; the start parameter was added in 2.6.
Syntax
The syntax of the enumerate() method is as follows:
enumerate(sequence, [start=0])
Parameters
- sequence -- a sequence, iterator, or other object that supports iteration.
- start -- the value of the starting position of the index.
Return Value
Returns an enumerate object.
Example
The following examples show the use of the enumerate() method:
seasons
=
[
'Spring'
,
'Summer'
,
'Fall'
,
'Winter'
]
list
(
enumerate
(
seasons
)
)
[
(
0
,
'Spring'
)
,
(
1
,
'Summer'
)
,
(
2
,
'Fall'
)
,
(
3
,
'Winter'
)
]
list
(
enumerate
(
seasons
,
start
=
1
)
)
Start the index from 1
[
(
1
,
'Spring'
)
,
(
2
,
'Summer'
)
,
(
3
,
'Fall'
)
,
(
4
,
'Winter'
)
]
A normal for loop
i
=
0
seq
=
[
'one'
,
'two'
,
'three'
]
for
element
in
seq:
...
i
,
seq
[
i
]
...
i
=
1
...
0
one
1
two
2
three
Using enumerate in a for loop
seq
=
[
'one'
,
'two'
,
'three'
]
for
i
,
element
in
enumerate
(
seq
)
:
...
i
,
element
...
0
one
1
two
2
three
Python built-in function