How to loop over lists in Python

1 min

Working with lists is fundamental in Python and there are many ways to do it.

  1. Simple for loop
  2. Index looping
  3. Enumerate
  4. List comprehension

Simple for loop

The normal loop that most people use.

my_list = ["A", "B", "C", "D"]

for value in my_list:

Index looping

This one utilizes the index of the list to access its value.

my_list = ["A", "B", "C", "D"]

for idx in range(len(my_list)):


This one is a built-in function in Python that will return both the index and the value.

my_list = ["A", "B", "C", "D"]

for idx, value in enumerate(my_list):
	print(idx, value)

List comprehension

This one is most often used to edit the values in a list.

my_list = ["A", "B", "C", "D"]

my_new_list = [value for value in my_list if value in ["A", "B"]]

Which one to use

Each method can greatly vary in terms of speed.

Here is the order I would use if I need to loop over a list in Python.

  1. List comprehension
  2. Simple loop
  3. Enumerate
  4. Index looping

Here you are! You now know how to loop over lists in Python.