by Team Codeasify
993
In this answer, with the help of examples, we'll learn and see how the Python enumerate()
method works.
Example 1: Here is an example of how to enumerate() function works in Python:
# Enumerate function: enumerate(iterable, start=0)
# An object of fruits list (supports iterator)
fruits = ["Apple", "Banana", "Grapes", "Pear", "BlueBerry"]
# Now change this fruits list objects to enumerate object
enumerate_fruits = enumerate(fruits) # Output: <class 'enumerate'>
print(tuple(enumerate_fruits))
# Output: ((0, 'Apple'), (1, 'Banana'), (2, 'Grapes'), (3, 'Pear'), (4, 'BlueBerry'))
The "enumerate" is a built-in function in Python. That converts a data collection object (Iterable objects like lists, tuples, or strings) into an enumerate object.
Or
We can say that the enumerate()
method adds a counter to an iterable.
This can be useful for iterating over a sequence and keeping track of the current index. It can also be useful for creating a list of tuples with the position and value of each element.
What is an enumerate object?
enumerate object is also an iterator that produces tuples containing the position (position = index of iterator values + start) and the value of each element of the iterable object.
As we already know `enumerate` is a function.
Input parameters
enumerate(iterable, start=0)
accept two parameters:
1. iterable (required, default = NA, type = iterator): A sequence or object that supports iteration.
2. start (optional: default = 0, type = int): A value from which to start counting for the position.
Return value
enumerate()
return an enumerate object that is also iterable.
Example 2: Let's see how we can use enumerate() function in loops.
# An object of fruits list
fruits = ["Apple", "Banana", "Grapes", "Pear", "BlueBerry"]
# Simply loop over the enumerate object
for fruit in enumerate(fruits):
print(fruit, end = " ") # Will print a tuple Ex. (0, 'Apple')
# Let's Unpack the tuple out of two variable in the loop itself
for position_index, fruit_name in enumerate(fruits):
print(position_index, fruit_name, end= "\n")
# Now let's change default start value
for position_index, fruit_name in enumerate(fruits, 10):
print(position_index, fruit_name, end = "\n")
Output:
# (0, 'Apple') (1, 'Banana') (2, 'Grapes') (3, 'Pear') (4, 'BlueBerry')
# 0 Apple
# 1 Banana
# 2 Grapes
# 3 Pear
# 4 BlueBerry
# 10 Apple
# 11 Banana
# 12 Grapes
# 13 Pear
# 14 BlueBerry
Hope you understood the complete concept of enumerate() function.
Thanks for visiting Codeasif.