PythonBuilt-in functions
enumerate()
Adds a counter to items while looping over them.
- Returns
- An iterator of
(index, item)pairs.
Example
#Python
ranking = ["Emma", "Mia", "Jack"]
for place, name in enumerate(ranking, start=1):
print(f"{place}. {name}")
print(list(enumerate("ab")))Resultsaved result, you can check it
1. Emma
2. Mia
3. Jack
[(0, 'a'), (1, 'b')]
Definition and usage
#The enumerate() function returns (index, item) pairs for the items of a collection. In a loop you unpack them right away: for i, item in enumerate(items).
The start parameter changes the first number of the counter. enumerate(items, start=1) numbers from one, which is handy when displaying a list for people to read.
It is a more readable and safer alternative to for i in range(len(items)), because you don't have to read items[i] by hand.
Syntax
#Syntax
enumerate(iterable, start=0)Parameters
#iterable
a collection
The items to number.start
int, default 0
The first value of the counter.
Good practices
#- Instead of
range(len(my_list)), useenumerate(my_list). - For numbering shown to users, set
start=1.
Related entries
#- forA loop that goes through the successive items of a sequence or other iterable object.
- zip()Pairs up (or groups into tuples) the matching items of several collections.
- range()Creates a sequence of integers, most often for a for loop.
- list()Creates a list, either empty or from the items of another iterable.
Spotted a mistake or missing an example? Write to us.