What Does enumerate() Do in Python?
Ever wondered what does enumerate do in Python? It's a simple yet powerful built-in function that allows you to loop over iterables while keeping track of the index—cleanly and efficiently.
๐ง What is enumerate()?
enumerate() adds a counter to an iterable (like a
list or tuple) and returns it as an enumerate object. This allows you to
access both the index and value during iteration.
๐งช Syntax
python
CopyEdit
enumerate(iterable, start=0)
- iterable:
The collection you want to loop through.
- start:
(Optional) The index to start counting from. Defaults to 0.
✅ Example Usage
Basic Loop
python
CopyEdit
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)
Start Index at 1
python
CopyEdit
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
List Comprehension with Enumerate
python
CopyEdit
indexed = [(i, x.upper()) for i, x in enumerate(['a', 'b', 'c'])]
๐ Why Use enumerate()?
- Cleaner
and more readable than manual counters
- Avoids
common mistakes like using .index() in loops
- Considered
more "Pythonic"
๐ Conclusion
If you're looping through an iterable and need the index
alongside each item, enumerate() is your go-to solution. It's fast, clean, and
makes your code easier to read.
Want to learn more Python tricks? Explore our full guide on what does enumerate do in Python.
Comments
Post a Comment