Built-in functions in Python are functions that are included in the Python programming language by default and can be used without the need for any external libraries or modules. They are part of the Python language itself and are designed to help developers perform common tasks quickly and easily. These functions cover a wide range of operations, from basic mathematical functions like abs() and round() to advanced string manipulation functions like split() and join(). One such built-in function is the enumerate function in python. In this article, we will learn about enumerate function in python with the help of examples.
What is Enumerate Function in Python?
The enumerate() function in Python is a built-in function that allows you to iterate over a sequence (like a list or a string) and keep track of the index of the current item. The function returns an enumerate object, which is an iterator that generates a sequence of tuples. Each tuple contains the index of the current item and the item itself.
Here is an example that demonstrates the use of enumerate():
fruits = ['mango', 'banana', 'apple', 'cherry'] for index, fruit in enumerate(fruits): print(index, fruit)
Output:
0 mango
1 banana
2 apple
3 cherry
Explanation – In this example, the enumerate() function is used to loop over the list of the fruits, and for each iteration, it returns a tuple that contains the index of the current fruit and the fruit itself. The for loop then unpacks the tuple into two variables, index, and fruit, which are printed to the console. This allows you to access both the index and the item in the sequence at the same time, which can be useful in many scenarios.
Syntax of Enumerate Function
The syntax for the enumerate() function in Python is as follows:
enumerate(iterable, start=0)
Here, iterable is the sequence that you want to iterate over, and start is an optional parameter that specifies the starting value of the index. The default value of the start is 0.
Parameters of Enumerate Function
The enumerate() function in Python has two parameters:
- iterable (required): This is the sequence that you want to iterate over. It can be any iterable object, such as a list, tuple, string, or dictionary.
- start (optional): This is an integer value that specifies the starting value of the index. The default value is 0, which means that the index starts at 0. However, you can specify a different starting value if you want the index to start at a different number.
Return Value of Enumerate Function
The enumerate() function in Python returns an enumerate object, which is an iterator that generates a sequence of tuples. Each tuple contains two values: the index of the current item in the sequence and the item itself.
You can use this enumerate object directly in a loop, or you can convert it to a list, tuple, or any other iterable object using the list() or tuple() function.
Examples of Enumerate Function in Python
Here are some examples of using the Enumerate Function in Python:
Example 1 – Creating a dictionary from a list of items with their corresponding indices as keys
Sol – Below is the code implementation and explanation of this example
persons = ['manoj', 'harsh', 'naman', 'himanshu'] person_dict = {index: value for index, value in enumerate(persons)} print(person_dict)
Output:
{0: 'manoj', 1: 'harsh', 2: 'naman', 3: 'himanshu'}
Explanation – In the above example, the enumerate() function is used to iterate over the list of the persons and return a tuple containing the index and value of each element. The dictionary comprehension then creates a new dictionary where the keys are the indices and the values are the corresponding person.
The index: person syntax inside the dictionary comprehension creates a key-value pair for each element in the list of persons. The resulting dictionary has the form {0: ‘manoj’, 1: ‘harsh’, 2: ‘naman’, 3: ‘himanshu’}.
This technique can be useful when you need to create a dictionary where the keys are the indices of the items in a list. You can then use the keys to quickly access the corresponding values in the dictionary.
Example 2 – Finding the index of the first occurrence of an item in a list
Sol – Below is the code implementation and explanation of this example.
fruits = ['apple', 'banana', 'cherry', 'banana'] banana_index = next(index for index, value in enumerate(fruits) if value == 'banana') print(banana_index)
Output:
1
Explanation – In this example, We loop over the list using enumerate(), which gives us the index and value of each element in the list. Inside the loop, we check if the current value is equal to the value we’re searching for, and if it is, we return the index. In the example above, the fruit ‘banana’ is found at index 1 in the list, so our output is 1.
Example 3 – Looping over a list of lists and accessing the indices and values of each item
Sol – Below is the code implementation and explanation of this example.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row_index, row in enumerate(matrix): for col_index, col in enumerate(row): print(f'({row_index}, {col_index}): {col}')
Output:
(0, 0): 1
(0, 1): 2
(0, 2): 3
(1, 0): 4
(1, 1): 5
(1, 2): 6
(2, 0): 7
(2, 1): 8
(2, 2): 9
Explanation – In this example, we have a list of lists called matrix that contains three sub-lists. We use the outer loop to iterate over each sub-list, and the inner loop to iterate over each item in each sub-list. We use enumerate to get the index and value of each item in each sub-list. In the output, each line shows the index of the outer list (i.e., the sub-list), the index of the inner list (i.e., the index of the item within the sub-list), and the value of the item.
Summary
- Enumerate() is a built-in Python function that allows you to iterate over a sequence and keep track of the index of each item.
- It takes a sequence (e.g., a list, tuple, or string) as input and returns an enumerate object, which is an iterator that generates a sequence of tuples.
- You can use the enumerate() function in a for loop to iterate over a sequence and access both the index and the item in the sequence at the same time.
- The enumerate() function can be used with a nested loop to iterate over a sequence of sequences (e.g., a list of lists).
- The enumerate() function is a useful tool for working with sequences in Python and can simplify your code by allowing you to access both the index and the item in a sequence at the same time.
FAQs Related to Enumerate() Function
Here are some Frequently Asked Questions on Enumerate Function in Python
Q1: What is the difference between enumerate() and range() in Python?
A: enumerate() and range() are two different functions in Python that are used for different purposes. range() is used to generate a sequence of numbers, whereas enumerate() is used to iterate over a sequence and keep track of the index of each item. You can use range() to generate a sequence of integers that you can use as indices, and then use those indices to access the items in the sequence. However, if you also need to keep track of the index while iterating over the sequence, then enumerate() is a better choice.
Q2: Can you use enumerate() with a step parameter?
A: No, the enumerate() function does not have a step parameter. If you want to iterate over a sequence with a step parameter, you can use range() to generate a sequence of indices and then use those indices to access the items in the sequence.
Q3: Is it possible to modify the index values returned by enumerate() in Python?
A: Yes, you can modify the index values returned by enumerate() by specifying a different starting value for the index using the start parameter. For example, if you want the index to start at 1 instead of 0, you can call enumerate() like this: enumerate(sequence, start=1). You can also modify the index values after they are returned by enumerate() by adding or subtracting a value.
Q4: Can you use enumerate() with a nested loop in Python?
A: Yes, you can use enumerate() with a nested loop in Python. If you have a sequence of sequences (e.g., a list of lists), you can use enumerate() to loop over the outer sequence and then use another loop to loop over the items in each inner sequence.