10. Enumerate

enumerate() is a built-in function that pairs each element with its index. Its signature is:

  • iterable — the collection to walk through, such as a list or a string.
  • start — the value of the first index. Default: 0.
  • It returns pairs (index, value), one per pass.

Unpack each pair into two names in the for header:

print(index, fruit) uses the default separator, so it prints 0 apple. To use a different layout, build an f-string: f"{index}: {fruit}".

Coming from JavaScript? enumerate(items) is items.entries(), but you unpack it directly in the loop header: for i, item in enumerate(items):.

#01

Print index and value

Use letters = ["a", "b"]. Loop over enumerate(letters) and print the index and the letter in one print() call.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Format the index and value

Use letters = ["a", "b"]. Loop over enumerate(letters) and print index: letter using an f-string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Start counting at one

Use letters = ["a", "b"]. Loop over enumerate(letters, start=1) and print the index and the letter in one print() call.

Print exactly:

Create a free account to save your progress and unlock chapter 2.