How to loop over lists in Python
• 1 minWorking with lists is fundamental in Python and there are many ways to do it.
- Simple for loop
- Index looping
- Enumerate
- List comprehension
Simple for loop
The normal loop that most people use.
my_list = ["A", "B", "C", "D"]
for value in my_list:
print(value)
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)):
print(my_list[idx])
Enumerate
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.
- List comprehension
- Simple loop
- Enumerate
- Index looping
Here you are! You now know how to loop over lists in Python.