In Python, the enumerate() function is a built-in function for iterating over an iterable (such as a list, tuple, string, or dictionary)
It adds a counter to the iterable and returns it as an enumerate object, which can then be converted into a list of tuples or used in a loop.
Each tuple contains a pair of the index and the corresponding value from the iterable.
EXAMPLE PROGRAM USING ENUMERATE() FUNCTION
syntax:enumerate(sequence,start)
sequence: any sequence like a string, list, set, etc.
Start (Optional): it indicates the start point of the counter. Its default value is 0
Example 1:
name="python" enumerate_name=enumerate(name) print(list(enumerate_name))
output: [(0, 'p'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]
Example 2:
set_a={1,2,3,4} enumerate_set=list(enumerate(set_a,10)) print(enumerate_set)
output: [(10, 1), (11, 2), (12, 3), (13, 4)]
Looping Over an Enumerate:
We can use the for loop to iterate over an enumerate.
Example 3:
name=["Jack", "john", "james"] for each_name in enumerate(name): print(each_name)
output: (0, 'Jack') (1, 'john') (2, 'james')
We can unpack each tuple returned by the enumerate
Example 4:
names=["jack", "john", "james"] for count, names in enumerate(names): tuple_a=(count,names) print(tuple_a)
output: (0, 'jack') (1, 'john') (2, 'james')