How to Iterate a Python List With Index?

Python has various built-in methods to iterate a list. The most common method is using “in” operator to iterate the python lists. But, they don’t allow us to use the index of the list items by default. So, I have shared 4 unique and easiest methods to iterate a python list with an index.

1. Using Enumerate Function

This is the easiest method. The first variable in the iteration points to the index of the item and the second variable points to the current list item. Here is a simple example to understand it easily.

countries = ['US', 'GB', 'CA', 'DE']
for index, item in enumerate(countries):
    print(index, item)

2. While Loop

In this method, we create a variable for storing the index of the item in the iteration. The while loop will end once it completes the iteration.

countries = ['US', 'GB', 'CA', 'DE']
index = 0
while index < len(countries):
    print(index, countries[index])
    index += 1

3. Length Function

It is very similar to the above while method, but here we don’t need to create any extra variables to store the index of the items. It will be done automatically using the len() method.

countries = ['US', 'GB', 'CA', 'DE']
for index in range(len(countries)):
    print(index, countries[index])

4. Using in Operator

We should create a variable to store the index of items and then iterate the items using the “in” operator to get the index of the items of the Python list.

countries = ['US', 'GB', 'CA', 'DE']
index = 0
for item in countries:
    print(index, item)
    index += 1

Suggested Solution

You can use any one of the above four methods as all of them are easy to implement and works almost in the same way.