enumerate()

Adds a counter to items while looping over them.

Returns
An iterator of (index, item) pairs.
On this page

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)), use enumerate(my_list).
  • For numbering shown to users, set start=1.

Related entries

#

Spotted a mistake or missing an example? Write to us.