The enumerate()
function in Python adds a counter to an iterable (like a list, tuple, or string) and returns it as an enumerate
object. It is commonly used in loops to access both the index and the value of each element in the iterable.
Syntax
enumerate(iterable, start=0)
iterable
: The sequence (e.g., list, tuple, string, etc.) to enumerate.start
(optional): The starting value of the counter (default is0
).
How enumerate()
Works
- Converts the input iterable into an enumerate object.
- Pairs each item in the iterable with an index starting from the specified value.
Examples
1. Basic Usage
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
2. Specifying a Start Value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
print(f"Index {index}: {fruit}")
Output:
Index 1: apple
Index 2: banana
Index 3: cherry
3. Using enumerate()
with Strings
word = "hello"
for index, char in enumerate(word):
print(f"Index {index}: {char}")
Output:
Index 0: h
Index 1: e
Index 2: l
Index 3: l
Index 4: o
4. Converting Enumerate to a List
You can convert an enumerate
object into a list of tuples.
numbers = [10, 20, 30]
enum_list = list(enumerate(numbers))
print(enum_list)
Output:
[(0, 10), (1, 20), (2, 30)]
5. Using enumerate()
in List Comprehension
fruits = ['apple', 'banana', 'cherry']
indexed_fruits = [f"{i}: {fruit}" for i, fruit in enumerate(fruits, start=1)]
print(indexed_fruits)
Output:
['1: apple', '2: banana', '3: cherry']
Advantages of Using enumerate()
- Simplifies access to both index and value in loops.
- Reduces the need for manual index tracking using counters.
- Makes the code more readable and Pythonic.
Common Use Cases
- Iterating through a list while keeping track of indices.
- Generating numbered lists.
- Debugging by pairing indices with elements.
enumerate()
is a powerful and elegant tool that is a staple for Python developers, making iteration tasks easier and more efficient.