Easy Tutorial
❮ Python Os Link Python Sum Array ❯

Python3 enumerate() Function

Python3 Built-in Functions


Description

The enumerate() function is used to combine an iterable data object (such as a list, tuple, or string) into an indexed sequence, listing both the data and the index. It is commonly used in for loops.

Syntax

Here is the syntax for the enumerate() method:

enumerate(sequence, [start=0])

Parameters

Return Value

Returns an enumerate (enumeration) object.


Examples

The following examples demonstrate the use of the enumerate() method:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # Index starts from 1
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Regular for Loop

i = 0
seq = ['one', 'two', 'three']
for element in seq:
    print(i, seq[i])
    i += 1

Output:

0 one
1 two
2 three

for Loop Using enumerate

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)

Output:

0 one
1 two
2 three

Python3 Built-in Functions

❮ Python Os Link Python Sum Array ❯