Enumerate in Python

What is Enumerate?

enumerate() is a built-in function in Python used to loop over an iterable while keeping track of the index of each item. It returns an enumerate object which yields pairs containing the index and the value.

Syntax

enumerate(iterable, start=0)

- iterable: any iterable object (like a list, tuple, or string)
- start: the index to start counting from (default is 0)

Examples

# 1. Using enumerate with a list
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry
  
# 2. Starting the index from 1
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)
# Output:
# 1 apple
# 2 banana
# 3 cherry
  
# 3. Converting enumerate object to a list
enumerated_list = list(enumerate(fruits))
print(enumerated_list)
# Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
  
# 4. Using enumerate with a string
for index, letter in enumerate("hello"):
    print(index, letter)
# Output:
# 0 h
# 1 e
# 2 l
# 3 l
# 4 o
  
# 5. Ignoring the index using underscore
for _, fruit in enumerate(fruits):
    print(fruit)
# Output:
# apple
# banana
# cherry