How to loop over lists in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Working 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.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚