How to Use enumerate() Function in Python: Syntax and Examples
The
enumerate() function in Python adds a counter to an iterable and returns it as an enumerate object of pairs containing the index and the item. You can use it in loops to get both the position and the value easily.Syntax
The enumerate() function has this basic syntax:
enumerate(iterable, start=0)
Here, iterable is any sequence like a list or string, and start is the number where counting begins (default is 0).
python
enumerate(iterable, start=0)
Example
This example shows how to use enumerate() in a for loop to get both index and value from a list:
python
fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits, start=1): print(f"{index}: {fruit}")
Output
1: apple
2: banana
3: cherry
Common Pitfalls
Some common mistakes when using enumerate() include:
- Forgetting to unpack the tuple into
indexandvalue. - Using
enumerate()without a loop, which returns an enumerate object that needs conversion to list or iteration. - Not setting
startwhen you want counting to begin from a number other than 0.
python
items = ['a', 'b', 'c'] # Wrong: forgetting to unpack for item in enumerate(items): print(item) # prints tuples, not separate index and value # Right: unpacking index and value for index, item in enumerate(items): print(index, item)
Output
(0, 'a')
(1, 'b')
(2, 'c')
0 a
1 b
2 c
Quick Reference
| Parameter | Description |
|---|---|
| iterable | Any sequence like list, tuple, or string to enumerate |
| start | Optional integer to start counting from (default 0) |
| Returns | An enumerate object yielding pairs (index, value) |
Key Takeaways
Use
enumerate() to get index and value pairs from any iterable in a loop.Remember to unpack the pairs into two variables, usually index and value.
You can change the starting index by setting the
start parameter.The
enumerate() function returns an iterable object, so use it in loops or convert to list.Avoid forgetting to unpack or misusing the enumerate object directly without iteration.