BYU logo Computer Science

Enumerate

We often want to loop through the items in a list:

prophets = ['Moses', 'Elijah', 'Nephi', 'Malachi', 'Alma']

for prophet in prophets:
    print(prophet)

Sometimes we want to use the index for a prophet, so we want to know which was 1st, which 2nd, etc.

prophets = ['Moses', 'Elijah', 'Nephi', 'Malachi', 'Alma']

for index in range(len(prophets)):
    print(f'{index}: {prophets[index]}')

This prints:

0: Moses
1: Elijah
2: Nephi
3: Malachi
4: Alma

There is an easier way to do this! We can use enumerate():

prophets = ['Moses', 'Elijah', 'Nephi', 'Malachi', 'Alma']

for index, prophet in enumerate(prophets):
    print(f'{index}: {prophet}')

Using enumerate(), we get a list of tuples we can iterate through: (index, item).

This lets us get both the index and the item as we go through the list, with simpler syntax.