Post

Python enumerate() Method

In this tutorial we will learn about python enumerate() method and its uses.

Python enumerate() Method

The enumerate() method adds a counter to an iterable and returns its enumerated object.

The syntax of enumerate() is:

1
2
enumerate(iterable, start=0)

enumerate() Parameters

enumerate() method takes two parameters:

iterable - A sequence, an iterator, or an object that supports iteration.

start - Starts counting from this number. If start is omitted, 0 is taken as a start. This is an Optional.

Let’s check some examples of python enumerate().

Example 1: How enumerate() works in python?

1
2
3
4
5
6
7
8
9
10
11
12
cars = ['BMW','Audi','Toyota']
enumerateCars = enumerate(cars)

print(type(enumerateCars))

print(list(enumerateCars))

# changing the default counter

enumerateCars = enumerate(cars, 10)
print(list(enumerateCars))

The output will be as follows.

1
2
3
4
<class 'enumerate'>
[(0, 'BMW'), (1, 'Audi'), (2, 'Toyota')]
[(10, 'BMW'), (11, 'Audi'), (12, 'Toyota')]

###

Example 2: Looping with an Enumerate object.

1
2
3
4
5
cars = ['BMW','Audi','Toyota']

for item in enumerate(cars):
    print(item)

Output:

1
2
3
4
(0, 'BMW')
(1, 'Audi')
(2, 'Toyota')

Rules of enumerate()

The enumerate() method takes a collection(e.g. a list) and returns it as an enumerate object.

The enumerate() method adds a counter as the key of the enumerate object.

This post is licensed under CC BY 4.0 by the author.