What is Enumeration in Python

If you are a programmer, you may have seen this question. What is Enumeration in Python? A data collection object is transformed into an enumerate object using the enumerate function in Python. Enumerate produces an object with a counter serving as a key for each value in the object, making it simpler to retrieve the collection’s contents. enumerate documentation in Python : enum

What is Enumeration in Python
What is Enumeration in Python

Python loops are often introduced by looping over a simple sequence. The range function is one of the tools you learn to use for this. When looping over a single item in a sequence, the range function outputs a series of integers.

The index of a series, or the sequence’s order, is sometimes crucial to know. Anytime you find a loop, other than through utilizing an index, within your code range(len(…)), use it instead! More often than you may imagine, this comes up in programming! The built-in function enumerates can be useful in this situation.

Syntax of enumerate function in Python

Let’s go through the basic syntax


enumerate(iterable, start)
Anything that can be iterated over can be the iterable for the enumerate function. We may specify the starting index to utilize by using the start option.

Enumerate example
So now lets do a simple example of the enumerate function

new_list = [‘a’,’b’,’c’,’d’,’e’]

[(0, ‘a’), (1, ‘b’), (2, ‘c’), (3, ‘d’), (4, ‘e’)]
See how each item on the list has an index? The index always comes first in the tuple and then the subsequent item in the list.

Python enumerate Program

# Python program to illustrate
# enumerate function
l1 = ["eat", "sleep", "repeat"]
s1 = "geek"
# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)
print ("Return type:", type(obj1))
print (list(enumerate(l1)))
# changing start index to 2 from 0
print (list(enumerate(s1, 2)))


Return type: 
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]


Data Structures related posts visit HERE

Python-related posts Visit HERE

C/C++ related posts Visit HERE

Databases related posts Visit HERE

Algorithms related posts visit HERE

Data Science related posts visit HERE

Share the Knowledge