python

Python3 program to iterate over a list

Iteration through a List in python version 3 can be done using for loop. The list in python can contains different items and we can access them using its index.

my_list = ["one", "two", "three", "four", "five"]

# Using for loop
for item in my_list:
    print(item)

# Using range by getting list length
for i in range(len(my_list)):
    print(my_list[i])
Output
one
two
three
four
five

Performance-wise you can choose the first method to iterate over the list using For loop without using an index.

There are more ways to iterate over a list which are described as below:

Iterate through List using enumerate()

You can use enumerate() function in for loop to iterate through a list. Below is the code example that you can use for that.

my_list = ["one", "two", "three", "four", "five"]

for index, value in enumerate(my_list):
    print (index, ": ",value)
Was this helpful?