Working With Iterables II
The enumerate() Function
Learn how enumerate() lets you loop over a list and access both the index and the value at the same time — no manual counter needed.
The built-in enumerate() function wraps any iterable and yields each item together with its position index. No manual counter needed.
Use enumerate() in a for-loop to get both index and value:
Python
Output
The syntax for enumerate():
Python
What will be the output?
Python
You can convert enumerate() to a list to see all pairs at once:
Python
Output
Pass start= to begin counting from a different number. Useful for 1-based rankings:
Python
Output
What will be the output?
Python
A common pattern: build a dict that maps each item to its index using enumerate().
Build a position lookup dict from a list:
Python
Output
What will be the output?
Python
enumerate() works inside list comprehensions too:
Python
Output
What will be the output?
Python
What will be the output?
Python
What will be the output?
Python