Thursday, January 30, 2025
HomeProgrammingHow to Access the Index Value in a ‘For’ Loop? - Python

How to Access the Index Value in a ‘For’ Loop? – Python

In Python, you can access the index value in a for loop using the built-in enumerate() function. This function returns both the index and the value as you iterate over an iterable, like a list. Here’s an example:

python
my_list = ['apple', 'banana', 'cherry']

for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")

The enumerate() function takes two arguments: the iterable and an optional start value (default is 0). It returns a tuple, where the first element is the index and the second is the corresponding value

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x