Nearby lessons
47 of 159Python - 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
Using a custom start value
Pass start=1 when the displayed numbering should begin at one.
Enumerating strings
Creating a list of pairs
The iterator can be consumed by list() when a materialized list is required.
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 QuestionsProgress: 0 / 8