Learning Sections show
Enumerate Function in Python
The enumerate
function in Python adds a counter to an iterable and returns it as an enumerate object. This is particularly useful when you need to have an index while iterating over a list or any other iterable.
1. Basic Usage
The basic syntax for enumerate
is:
enumerate(iterable, start=0)
Here, iterable
is the iterable to be enumerated, and start
is the index value from which the counter is to be started (default is 0).
2. Example Usage
Consider the following example where we enumerate over a list of fruits:
# Example of using enumerate
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
3. Using start parameter
The start
parameter allows you to specify the starting index:
# Using start parameter with enumerate
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, 1):
print(f"{index}: {fruit}")
# Output:
# 1: apple
# 2: banana
# 3: cherry
4. Converting to list
You can convert the enumerate object to a list if needed:
# Convert enumerate object to list
fruits = ['apple', 'banana', 'cherry']
enumerate_list = list(enumerate(fruits))
print(enumerate_list) # Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
5. Enumerate with different iterables
The enumerate
function can be used with different types of iterables such as tuples and strings:
# Enumerate with a tuple
fruits_tuple = ('apple', 'banana', 'cherry')
for index, fruit in enumerate(fruits_tuple):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
# Enumerate with a string
word = 'python'
for index, letter in enumerate(word):
print(f"{index}: {letter}")
# Output:
# 0: p
# 1: y
# 2: t
# 3: h
# 4: o
# 5: n