enumerate function in python
python have many in-built functions , in that today we will explore "enumerate()" function.
Python's built-in function enumerate(). This function is useful for obtaining an indexed list. For example, suppose you had a list of people that arrived at a party you are hosting. The list is ordered by arrival (Jhonny was the first to arrive, followed by Krogger, etc.):
names = ['Jhonny', 'Krogger', 'Elaime', 'Geoffery', 'Newton']If you wanted to attach an index representing a person's arrival order, you could use the following for loop:
indexed_names = []
for i,name in enumerate(names):
index_name = (i,name)
indexed_names.append(index_name)
print(indexed_names)
output:
[(0,'Jhonny'),(1,'Krogger'),(2,'Elaime'),(3,'Geoffery'),(4,'Newton')]explanation:
By using the enumerate() function in Python, which is a built-in function that allows you to loop over a list (or other iterable) and have an automatic counter.
for loop is used with enumerate(names). This returns a tuple for each element in the list names, where the first element of the tuple is the index and the second element is the value from the list.
These tuples are then appended to the indexed_names list.
we can rewrite the above for loop using list comprehension
indexed_names_comp = [(i,name) for i,name in enumerate(names)]
print(indexed_names_comp)output :
[(0,'Jhonny'),(1,'Krogger'),(2,'Elaime'),(3,'Geoffery'),(4,'Newton')]explanation:
The same operation is performed but using “list comprehension”, which is a more concise way to create lists in Python.
The expression (i,name) for i,name in enumerate(names) generates a list of tuples in the same way as the for loop in the first part, but does it in a single line of code.
we can re-write the above code with index number as specified by developer
# Unpack an enumerate object with a starting index of one
indexed_names_unpack = [*enumerate(names, 1)]
print(indexed_names_unpack)output:
[(1,'Jhonny'),(2,'Krogger'),(3,'Elaime'),(4,'Geoffery'),(5,'Newton')]explanation :
The enumerate() function is used again, but this time with a second argument 1, which sets the start value of the index.
The * operator is used to unpack the enumerate object into a list of tuples, which is assigned to indexed_names_unpack. This results in a list where the indices start at 1 instead of 0.
we will now execute the same piece of code in “spyder” and output will be as below


