in Python by (23.9k points)
What Do You Know About The Python Enumerate?

1 Answer

0 votes
by (31.6k points)

While using the iterators, sometimes we might have a use case to store the count of iterations. Python gets this task quite easy for us by giving a built-in method known as the enumerate().

The enumerate() function attaches a counter variable to an iterable and returns it as the “enumerated” object.

We can use this object directly in the “for” loops or transform it into a list of tuples by calling the list() method. It has the following signature:

enumerate(iterable, to_begin=0)


iterable: array type object which enables iteration

to_begin: the base index for the counter is to get started, its default value is 0

# Example - enumerate function 

alist = ["apple","mango", "orange"] 

astr = "banana"


# Let's set the enumerate objects 

list_obj = enumerate(alist) 

str_obj = enumerate(astr) 


print("list_obj type:", type(list_obj))

print("str_obj type:", type(str_obj))

print(list(enumerate(alist)) )  

# Move the starting index to two from zero

print(list(enumerate(astr, 2)))

The output is:

list_obj type: <class 'enumerate'>

str_obj type: <class 'enumerate'>

[(0, 'apple'), (1, 'mango'), (2, 'orange')]

[(2, 'b'), (3, 'a'), (4, 'n'), (5, 'a'), (6, 'n'), (7, 'a')]

Related questions

0 votes
asked Feb 10, 2021 in Python by SakshiSharma (32.2k points)