Nearby lessons

47 of 159

Python - enumerate() Function

📌 What You Will Learn
  • Explain what enumerate() returns
  • Loop over indexes and values together
  • Use the start argument for custom numbering
  • Convert enumerate objects to lists when needed
  • Choose enumerate() instead of manual counters

Why enumerate() is useful

When a loop needs both the position and the item, enumerate() is clearer and safer than maintaining a separate counter.

Basic syntax

The syntax is enumerate(iterable, start=0). It returns an enumerate iterator that produces (index, value) pairs.

Loop over indexes and values

🐍Code Cell
1colors = ['red', 'green', 'blue']
2 
3for index, color in enumerate(colors):
4 print(index, color)
Output
0 red
1 green
2 blue

Using a custom start value

Pass start=1 when the displayed numbering should begin at one.

🐍Code Cell
1colors = ['red', 'green', 'blue']
2 
3for number, color in enumerate(colors, start=1):
4 print(f'{number}. {color}')
Output
1. red
2. green
3. blue

Enumerating strings

🐍Code Cell
1for position, letter in enumerate('Python', start=1):
2 print(position, letter)
Output
1 P
2 y
3 t
4 h
5 o
6 n

Creating a list of pairs

The iterator can be consumed by list() when a materialized list is required.

🐍Code Cell
1pairs = list(enumerate(['a', 'b'], start=1))
2print(pairs)
Output
[(1, 'a'), (2, 'b')]

enumerate() versus a manual counter

A manual counter must be initialized and incremented correctly. enumerate() keeps the index synchronized with iteration and communicates the intent directly.

Common mistakes

  • Remember that the default index is zero.
  • Do not use enumerate() when only the values are needed.
  • Unpack exactly two variables for the index and value.
📝 Key Takeaways
  • enumerate() yields pairs containing an index and a value
  • The default index starts at zero
  • start changes the first index without changing the iterable
  • Tuple unpacking makes enumerate loops easy to read
  • enumerate() works with strings, lists, tuples, and other iterables

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8