Python Program to Access Index of a List Using for Loop


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In Python, a list is a collection of items that are ordered and changeable. Each item in a list has a specific index, which is its position in the list. The index of the first item in the list is always 0, the index of the second item is 1, and so on.

You can access items in a list by using their index. For example, if you have a list called fruits containing “apple”, “banana”, and “cherry”, you can access the second item in the list (which is “banana”) like this:


fruits = ["apple", "banana", "cherry"]
print(fruits[1])

The output will be :


banana


Python Code :

The below Python program accesses the index of a list using a for loop:



# Define a list of items
items = ['apple', 'banana', 'orange', 'grape']

# Loop through the list using enumerate()
for index, item in enumerate(items):
    print(f"The item at index {index} is {item}.")

Output:

The item at index 0 is apple.
The item at index 1 is banana.
The item at index 2 is orange.
The item at index 3 is grape.

In this program, we first define a list of items called items. We then loop through the list using the enumerate() function. The enumerate() function returns both the index and the value of each item in the list.

Inside the loop, we print a message that displays the index and value of each item in the list. The f-string is used to format the message with the values of index and item.

Note that the index of the first item in the list is 0, not 1.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co