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

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

To access the index value in a Python for loop, use the enumerate() function. It adds an index to each item being iterated over. Here’s an example:

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

for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")

The enumerate() function starts indexing at 0 by default, but you can specify a custom starting index:

python
for index, fruit in enumerate(fruits, start=1):
print(f"Index: {index}, Fruit: {fruit}")

This approach is concise and improves readability when you need both the index and the item during iteration.

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