Python enumerate() and loop - How to iterate the list, tuple, dictionary using the enumerate()

The enumerate() returns an enumerate object in which you can iterate and get the pair of the index and element.

a = ['com', 'org', 'net']

for p in enumerate(a):

# (0, 'com')
# (1, 'org')
# (2, 'net')

A list can be enumerated and each item in the for statement is a tuple of the index and value.

Enumerate a tuple

t = ('C#', 'Python', 'JavaScript')

for index, value in enumerate(t):
    print(f'{index} = {value}')

# 0 = C#
# 1 = Python
# 2 = JavaScript

A tuple can be enumerated. The f prefix in the above code represents the Python f-string.

Enumerate a dictionary

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

for pair in enumerate(d):

# (0, 'CA')
# (1, 'NV')
# (2, 'TX')

for pair in d.items():

# ('CA', 'California')
# ('NV', 'Nevada')
# ('TX', 'Texas')

A Python dictionary has pairs and you can get the index of each pair to use enumerate(). To get the keys and values of it, use items().


Powered by Markdown