Enumerate() in Python

Enumerate in Python :

Sometimes we need to keep count of iterators or the index position of an sequence  so that we can use the index of the sequence later in the code as per need. Enumerate() function adds a counter to an iterable and returns it in a form of enumerate object. This can be directly used or can be converted into a list of tuples.

enumerate in python

Enumerate in Python

Python has a built-in function to do this work which is enumerate() and it allows us to iterate over an iterable while keeping track of both the index and the value of each value in the iterable. 

Syntax : 

  enumerate(iterable,start)

iterable – any object that is iterable 

start(optional) – from index value to start, default value is 0

Return Value from enumerate()

enumerate() function adds counter to an iterable and returns it. The returned object is a enumerate object.

You can convert enumerate objects to list of tuple using list().

Code :

Run
#Enumerate
b='PrepInsta'             
print(list(enumerate(b,2))) 
enlist=enumerate(b)
for ind,char in enlist:
    print(ind,char)

Output :

[[(2, 'P'), (3, 'r'), (4, 'e'), (5, 'p'), (6, 'I'), (7, 'n'), (8, 's'), (9, 't'), (10, 'a')]
0 P
1 r
2 e
3 p
4 I
5 n
6 s
7 t
8 a

In the above program start(parameter) value is 2 so counter starts from 2 instead of 0. we can print the tuple value seprately also.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription