Python enumerate() Function
The enumerate()
function adds a counter to an iterable and returns it as an enumerate object (iterator with index and the value).
Syntax
enumerate(iterable, start)
enumerate() Parameters
Python enumerate()
function parameters:
Parameter | Condition | Description |
---|---|---|
iterable | Required | An iterable (e.g. list, tuple, string, etc.) |
start | Optional | A number to start counting from. Default value is 0. |
By default, enumerate()
starts counting at 0 but if you add a second argument start, it will start from that number instead.
enumerate() Return Value
Python enumerate()
function adds a counter to an iterable and returns it: the returned object is an enumerate object.
An enumerate object is an iterator that produces a sequence of tuples, each containing an index and the value from the iterable.
You can convert enumerate objects to lists and tuples using list()
and tuple()
functions, respectively.
Examples
Basic Example with Python enumerate() function
Create a list that can be enumerated:
color_list = ['red', 'green', 'blue']
result = list(enumerate(color_list))
print(result) # Output: [(0, 'red'), (1, 'green'), (2, 'blue')]
output
[(0, 'red'), (1, 'green'), (2, 'blue')]
You can change the default counter in enumerate()
as you need by specifying the start argument:
# set default counter to 10
color_list = ['red', 'green', 'blue']
result = list(enumerate(color_list, 10))
print(result) # Output: [(10, 'red'), (11, 'green'), (12, 'blue')]
output
[(10, 'red'), (11, 'green'), (12, 'blue')]
Example: loop over an Enumerate Object
When you iterate an enumerate object, you get a tuple containing (counter, item)
color_list = ['red', 'green', 'blue']
for pair in enumerate(color_list):
print(pair)
output
(0, 'red')
(1, 'green')
(2, 'blue')
However, you can unpack the tuple into multiple variables as well:
color_list = ['red', 'green', 'blue']
for index, item in enumerate(color_list):
print(index, item)
output
0 red
1 green
2 blue
And you can also change the default counter and loop:
color_list = ['red', 'green', 'blue']
for index, item in enumerate(color_list, 10):
print(index, item)
output
10 red
11 green
12 blue
Example: access the next element with next() function
color_list = ['red', 'green', 'blue']
enumerate_colors = enumerate(color_list)
# accessing the next element
next_element = next(enumerate_colors)
print(f"Next Element: {next_element}")
output
Next Element: (0, 'red')
To learn more, visit Python next()
function.