Python enumerate() function

Published February 15, 2022

When working with iterators in programming, we must unquestionably enumerate them. The Python enumerate() function makes it simple for programmers to count the number of iterations. This method sets the iterable's counter and returns it as an enumerating object. The enumerated objects can be used directly in loops by programmers, or they can be converted into a list of turples using the list () function.

 

Syntax

The syntax for the enumerate() method is as follows:

 

enumerate(iterable, start=0)

Where; iterable- an object which supports iteration

Start- an index value where  counter can be started  and the default is 0.

 

Example

x = ["a","b","c"]

y = "python"

obj1 = enumerate(x)

obj2 = enumerate(y)

print ("Return type:",type(obj1))

print (list(enumerate(x)))

print (list(enumerate(y,2)))

 

Output

Return type: <class 'enumerate'>
[(0, 'a'), (1, 'b'), (2, 'c')]
[(2, 'p'), (3, 'y'), (4, 't'), (5, 'h'), (6, 'o'), (7, 'n')]

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

259 Views