
๐Python Enumerate() Function: Complete Guide with Examples
Python Enumerate() Function: The enumerate() function in Python is a powerful built-in feature that simplifies looping by adding a counter to iterable objects. It efficiently tracks indexes while iterating over lists, tuples, dictionaries, and strings.
๐What is Python Enumerate()?
Python Enumerate() Function : The enumerate() function takes an iterable object and returns an enumerate object with a counter assigned to each item. This makes it easier to track index positions during iteration.
๐Python Enumerate() Function Syntax
python
enumerate(iterable, startIndex)
๐Parameters:
- iterable: The object you want to loop through (e.g., list, tuple, string, etc.).
- startIndex (optional): The starting count value. By default, the counter starts from 0.
๐Return Value:
Returns an enumerate object containing pairs of index and corresponding values.
๐Examples of Python Enumerate()
๐1. Using enumerate() with a List
python
mylist = [‘A’, ‘B’, ‘C’, ‘D’]
e_list = enumerate(mylist)
print(list(e_list))
๐Output:
css
[(0, ‘A’), (1, ‘B’), (2, ‘C’), (3, ‘D’)]
๐2. Using enumerate() with a Start Index
python
mylist = [‘A’, ‘B’, ‘C’, ‘D’]
e_list = enumerate(mylist, 2)
print(list(e_list))
๐Output:
[(2, ‘A’), (3, ‘B’), (4, ‘C’), (5, ‘D’)]
css
๐3. Looping Over an Enumerate Object
python
mylist = [‘A’, ‘B’, ‘C’, ‘D’]
for i in enumerate(mylist):
print(i)
print(“Using startIndex as 10”)
for i in enumerate(mylist, 10):
print(i)
๐Output:
vbnet
(0, ‘A’)
(1, ‘B’)
(2, ‘C’)
(3, ‘D’)
Using startIndex as 10
(10, ‘A’)
(11, ‘B’)
(12, ‘C’)
(13, ‘D’)
๐4. Enumerating a Tuple
python
my_tuple = (“A”, “B”, “C”, “D”, “E”)
for i in enumerate(my_tuple):
print(i)
๐Output:
arduino
(0, ‘A’)
(1, ‘B’)
(2, ‘C’)
(3, ‘D’)
(4, ‘E’)
๐5. Enumerating a String
python
my_str = “Python”
for i in enumerate(my_str):
print(i)
๐Output:
arduino
(0, ‘P’)
(1, ‘y’)
(2, ‘t’)
(3, ‘h’)
(4, ‘o’)
(5, ‘n’)
๐6. Enumerating a Dictionary
python
my_dict = {“a”: “PHP”, “b”: “JAVA”, “c”: “PYTHON”, “d”: “NODEJS”}
for i in enumerate(my_dict):
print(i)
๐Output:
arduino
(0, ‘a’)
(1, ‘b’)
(2, ‘c’)
(3, ‘d’)
๐Advantages of Using Enumerate in Python
โ
Simplifies tracking index values in loops.
โ
Efficient alternative to using list.index() in loops.
โ
Reduces the need for manual counter management in iteration.
โ
Supports multiple data structures like lists, tuples, dictionaries, and strings.
๐Summary
The Python enumerate() function is an essential tool for developers working with iterable objects. By combining both index tracking and iteration, it offers a cleaner and more efficient way to manage data structures. Mastering enumerate() can significantly improve your coding efficiency in Python.