In Python, you can use the built-in enumerate()
function to access the index of each element in a for
loop. The enumerate()
function takes an iterable (e.g., a list, tuple, or string) as an argument and returns a sequence of pairs, where each pair contains the index of the element and the element itself. Here’s an example:
fruits = [‘apple’, ‘banana’, ‘cherry’]
# Using enumerate() to access the index and the element in a for loop
for i, fruit in enumerate(fruits):
print(i, fruit)
Output:
0 apple
1 banana
2 cherry
1 banana
2 cherry
- sunny asked 1 month ago
- You must login to post comments
Your Answer
Please login first to submit.