How to loop over lists in Python

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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:
	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.

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

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

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.