Python Program to Access the Index of a List Using for Loop – 2024

Hey guys, in this blog we will see a Python Program to Access the Index of a List Using for Loop.

Example 1: Using enumerate

# Python Program to Access the Index of a List Using for Loop

my_list = [13, 4, 12, 1, 18, 42]

for index, val in enumerate(my_list):
    print(index, val)

Output

0  13
1   4
2  12
3   1
4  18
5  42
  • Here we traversed in the list using a for-loop.
  • We have used an enumerate that will associate an index value with every value of the list.
  • This will start the index with 0.

Example 2: Start the indexing with a non-zero value

# Python Program to Access the Index of a List Using for Loop

my_list = [13, 4, 12, 1, 18, 42]

for index, val in enumerate(my_list, start=1):
    print(index, val)

Output

1  13
2   4
3  12
4   1
5  18
6  42
  • Here we traversed in the list using a for-loop.
  • We have used an enumerate that will associate an index value with every value of the list.
  • This will start the index with 1.

Example 3: Without using enumerate()

# Python Program to Access the Index of a List Using for Loop

my_list = [13, 4, 12, 1, 18, 42]

for index in range(len(my_list)):
    value = my_list[index]
    print(index, value)

Output

0  13
1   4
2  12
3   1
4  18
5  42
  • First of all, we calculated the length of the list using the len().
  • Then we used the range function to create a list of numbers till the length and then we traversed in the list using a for-loop.
  • When index = 0, value=list[index] = list[0] = 13
  • This will start the index with 0.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

Your email address will not be published. Required fields are marked *