How to Use Enumerate Function in Python


In this example, we will learn how to use enumerate function in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))

# Conventional traversal
for i in range (len(seasons)):
    print( i ,seasons[i])
print()
# Traversing with the enumerate function
for index, item in enumerate(seasons):
    print( index, item)
print()
# Numerate can also receive the second parameter, which is used to specify the starting value of the index, such as:
for index, item in enumerate(seasons,2):
    print( index, item)

Output:

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
0 Spring
1 Summer
2 Fall
3 Winter

0 Spring
1 Summer
2 Fall
3 Winter

2 Spring
3 Summer
4 Fall
5 Winter
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments