Categories

Dec 22, 2019 in Python
Q: What Do You Know About The Python Enumerate?

1 Answer

Dec 22, 2019

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)

Arguments:

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')]

Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
Apr 15 in Robotic Process Automation
Dec 10, 2019 in Interview Question
Sep 13 in Agile
...