(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python enumerate() function
Updated on Jan 07, 2020
The enumerate()
function takes an iterable and returns an enumerate object (an iterator) that produces a tuple of the form (index, value)
, where index
refers to the offset of the item and item
refers to the corresponding item from the iterable.
The syntax of enumerate()
function is as follows:
Syntax:
enumerate(iterable[, start=0]) -> iterator for index, value of iterable
PARAMETER | DESCRIPTION |
---|---|
iterable |
(required) Any iterable object like string, list, dictionary, etc. |
start (optional) |
Initial value of the index . It defaults to 0 . |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>>
>>> list(enumerate("hello"))
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
>>>
>>>
>>> for index, value in enumerate("hello"):
... print(index, value)
...
0 h
1 e
2 l
3 l
4 o
>>>
|
Try it out:
The following listing shows how enumerate()
works with a list, dictionary and tuple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | >>>
>>> for index, value in enumerate([110, 45, 12, 891, "one"]):
... print(index, value)
...
0 110
1 45
2 12
3 891
4 one
>>>
>>>
>>> for index, value in enumerate({'name': 'Jane', 'age': 26, 'salary': 40000}):
... print(index, value)
...
0 name
1 salary
2 age
>>>
>>>
>>> for index, value in enumerate({1, 290, -88, 10}):
... print(index, value)
...
0 -88
1 1
2 10
3 290
>>>
|
Try it out:
Setting the initial value of the index #
To set the initial value of the index, we use the start
keyword argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>>
>>> list(enumerate("hello", start=2))
[(2, 'h'), (3, 'e'), (4, 'l'), (5, 'l'), (6, 'o')]
>>>
>>>
>>> for index, value in enumerate("hello", start=2):
... print(index, value)
...
2 h
3 e
4 l
5 l
6 o
>>>
|
Try it out:
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments