How to access the index in Python 'for' loops?

0
0

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
  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.