How to do list comprehension 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.
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 a real-world example
students = ["John Smith", "Will Smith", "Aretha Franklin", "Jimmy Hendrix"]
smith_students = [each for each in students if "Smith" in each]
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")]
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]
students_age = [15, 25, 21, 12, 15, 32]
has_majority = [True if each >= 18 else False for each in students_age]
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:
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. 📚