Enumerate

Enumerate

Built-in function of Python.

Allows us to loop over something and have an automatic counter.

Example:

for counter, value in enumerate(some_list):
    print(counter, value)

Accepts an optional argument which allows to tell enumerate from where to start the index.

my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
    print(c, value)

# Output:
# 1 apple
# 2 banana
# 3 grapes
# 4 pear

Example: create tuples containing the index and list item using a list:

my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print(counter_list)
# Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]

Last updated