Python – Print list with index

Python – Print list with index

In Python, you can print elements of a list along with the respective index using a For loop with enumerated list, or a While loop with a counter for index.

In this tutorial, we shall go through some examples where we take a list of elements, and print the elements in the list along with their index.

1. Print list with index using For loop in Python

In the following program, we use For loop to iterate over the enumerated list of given list. Enumeration gives us access to both index and element.

Python Program

x = ['apple', 'banana', 'cherry']

for index, element in enumerate(x):
    print(index, element)
Run Code Copy

Output

0 apple
1 banana
2 cherry

2. Print list with index using While loop in Python

In the following program, we use While loop to iterate over the given list. We shall maintain a counter index that starts at zero before while loop, and increments by one for each iteration of the loop, thus mimicking the index of elements in the list.

Python Program

x = ['apple', 'banana', 'cherry']

index = 0
while index < len(x):
    element = x[index]
    print(index, element)
    index += 1
Run Code Copy

Output

0 apple
1 banana
2 cherry

Please note that we increment the index in While loop. If this step is missed, then the While loop becomes Infinite While loop and runs indefinitely.

Summary

In this tutorial, we have seen how to print elements in a list along with the respective indices using For loop with enumerated list, or a While loop with counter.

Related Tutorials

Code copied to clipboard successfully 👍