Python Built-in Function enumerate:
The enumerate() is a built-in function in Python that returns an enumerated object from the iterable. However, the iterable must be a sequence, an iterator, or an object that supports iteration. In other words, it returns a tuple containing index and values from an iterable. So, each call on this enumerated object returns a tuple.
The signature for the enumerate() function is as shown below.
Parameters and return type
- This function takes two parameters. The first parameter will be a sequence, an iterator or an object that supports iteration. At the same time, the second parameter is optional and takes an integer value representing the starting value of an index in the tuples.
- However, it returns an enumerated object.
Python Built-in Function enumerate Examples:
Example 1: We will take a list of cities and create an enumerate object from this list. As the start parameter is not given, it will take 0 as a starting number by default. After that, we will use for loop to iterate over an enumerate object and print the same.
#Initializing c=["Delhi","Mumbai","Pune"] #Using enumerate and Printing r = enumerate(c) for i in r: print(i)
(0, 'Delhi') (1, 'Mumbai') (2, 'Pune')
Example 2: We will demonstrate an enumerate function with a start parameter in this case. So, the number starting from 100 are assigned to the values of the list. As a result, tuples that are generated will have a numbering from 100.
#Initializing c=["Delhi","Mumbai","Pune"] #Using enumerate and Printing r = enumerate(c, start=100) for i in r: print(i)
(100, 'Delhi') (101, 'Mumbai') (102, 'Pune')
Example 3: Let us take a list containing the city names for this example. Firstly, we will take both the parameters a list and a starting value. As a result, it will generate a list from the tuples of an enumerate.
#Initializing c=["Delhi","Mumbai","Pune"] #Using enumerate and Printing print(list(enumerate(c, start=111)))
[(111, 'Delhi'), (112, 'Mumbai'), (113, 'Pune')]
Hence, the enumerate() function returns an enumerate object as a tuple containing a number and an element from an iterable.
Happy Learning 🙂