How to Use Enumerate Function in PythonPython Basics


The enumerate() method adds counter to an iterable and returns it as an enumerate object.

Example

#!/usr/bin/python3

direction = ['East', 'South', 'West', 'North']
print(list(enumerate(direction)))

print(list(enumerate(direction, start = 1)) )
Output:

[(0, 'East'), (1, 'South'), (2, 'West'), (3, 'North')]
[(1, 'East'), (2, 'South'), (3, 'West'), (4, 'North')]

Syntax

enumerate(iterable, start = 0)

Parameters

Name Description
iterable A sequence, an iterator, or objects that support iteration
start A number. Enumerate() starts counting from this number

Return Value

It returns an enumerate object of the given iterable.


In this example we will show 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

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us