Enumerate() in Python

PythonServer Side ProgrammingProgramming

When using the iterators, we need to keep track of the number of items in the iterator. This is achieved by an in-built method called enumerate(). The enumerate() method adds counter to the iterable. The returned object is a enumerate object. Its syntax and parameters are described below.

enumerate(iterable, start=0)
iterable - a sequence, an iterator, or objects that supports iteration
start – is the position in the iterator from where the counting starts.
Default is 0.

Example

In the below example we take a dictionary and apply enumerate to it. In the result the default start is from 0 and we get the result printed starting with counter value as zero. We can also change the default start value to 5 and see a different result though the count remains same.

days= { 'Mon', 'Tue', 'Wed','Thu'}
enum_days = enumerate(days)
print(type(enum_days))

# converting it to alist
print(list(enum_days))

# changing the default counter to 5
enum_days = enumerate(days, 5)
print(list(enum_days))

Output

Running the above code gives us the following result −

[(0, 'Tue'), (1, 'Thu'), (2, 'Mon'), (3, 'Wed')]
[(5, 'Tue'), (6, 'Thu'), (7, 'Mon'), (8, 'Wed')]

Using Loops for enumerate

We can also use the code for looping and print the elements of the loop separately as shown in the code below.

Example

 Live Demo

days= { 'Mon', 'Tue', 'Wed','Thu'}
enum_days = enumerate(days)
# enumearte using loop
for enum_days in enumerate(days):
   print(enum_days)

for count,enum_days in enumerate(days,5):
   print(count,enum_days)

Output

Running the above code gives us the following result −

(0, 'Thu')
(1, 'Tue')
(2, 'Wed')
(3, 'Mon')
5 Thu
6 Tue
7 Wed
8 Mon
raja
Published on 17-Oct-2019 12:33:16
Advertisements