How to do list comprehension in Python

1 min

List comprehension are an extremely useful tool when you want to filter out elements in a list.

There is two major ways to do this

With an if condition

newlist = [expression for item in iterable if condition == True]
Here is the logic with an if condition

Here is a real-world example

students = ["John Smith", "Will Smith", "Aretha Franklin", "Jimmy Hendrix"]

smith_students = [each for each in students if "Smith" in each]
How to do a list comprehension with text variables

another one that checks for csv files only

my_file_list = ["january-sales.csv", "product-list.csv", "project.pdf", "february-sales.csv"]

only_csv = [each for each in my_file_list if each.endswith(".csv")]
How to do a list comprehension and filter for CSVs

With an if else condition

This one is useful when you need to fill in a DataFrame, because it will keep the same length as the original list but return something different depending on your if condition.

newlist = [expression if condition == True else value for item in iterable]
Here is the logic with an if else condition
students_age = [15, 25, 21, 12, 15, 32]

has_majority = [True if each >= 18 else False for each in students_age]
Here is the logic with an if else condition to check for majority

Here you are! You now know how to do a list comprehension in Python!

More on fundamentals

If you want to know more about Python fundamentals without headaches... check out the other articles I wrote by clicking just here:

Fundamentals - The Python You Need
We gathered the only Python essentials that you will probably ever need.