When working with iterators, we frequently need to track how many iterations have been completed. Python makes this work easier for programmers by including an enumerate() function. Enumerate() method adds a counter to an iterable and returns it as an enumerating object. This enumerated object can then be used in loops directly or converted to a list of tuples with the list() method.
Enumerate() in Python
- Iterable: It refers to any object that supports iteration
- Start: It refers to the index value from which the counter is to be started; by default, it is 0
Enumerate() objects in loops
The enumerate() function returns an enumerated object from a collection (such as a tuple). The counter is added as the key of the enumerated object by the enumerate() function.
Example: converting a tuple into an enumerate object
laptops = ('Apple', 'HP', 'DELL') y = enumerate(laptops) list(y)
How does enumerate() work?
The enumerate() function returns an iterator called an enumerate object. A tuple comprising the index and element at that index is returned for each element fetched from this enumerate object: (index, element). With the for loop’s every iteration, the elements of the returned tuple are assigned to the index and element variables. To put it another way, the returned tuple is unpacked within the for-statement:
for index, element in enumerate(num_list): # similar to: index, element = (index, element)
The following example demonstrates these tuples more clearly:
students_list = ['Ann', 'Joy', 'Thomson'] list(enumerate(students_list))
The list() function on the enumerated object (the iterator) provides a list of tuples, each containing the index and its matching element or value.
Example 1: How does enumerate() work in Python?
laptops = ['HP', 'DELL', 'Chromebook'] enumerateLaptops = enumerate(laptops) print(type(enumerateLaptops)) # converting to list print(list(enumerateLaptops)) # changing the default counter enumerateLaptops = enumerate(laptops, 10) print(list(enumerateLaptops))
Example 2: Enumerate object – Looping Over
laptops = ['HP', 'DELL', 'Chromebook'] for machine in enumerate(laptops): print(machine) print('\n') for count, machine in enumerate(laptops): print(count, machine) print('\n') # changing default start value for count, machine in enumerate(laptops, 100): print(count, machine)
The Python library includes a built-in method called Enumerate(). It receives a collection of tuples as input and produces an enumerated object. Enumerate() adds a counter to each item of an iterable object and delivers an enumerate object as an output string in Python.
Python’s enumerate() function helps you create Pythonic for loops when you need a count and the value from an iterable. Enumerate () gives a tuple containing the number and value, which means you don’t have to increment the counter yourself is a significant plus. It also gives you the option of changing the counter’s beginning value.