4. Lists
4.6 List comprehension
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
A list comprehension builds a new list in one line: [expression for item in list if condition].
It is the everyday way to clean or filter a column of data.
Example
names = [" Asha", "RAVI ", " neha"]
clean = [n.strip().title() for n in names]
print(clean)
amounts = [250, -10, 1200, 0, 75]
valid = [a for a in amounts if a > 0]
print(valid)['Asha', 'Ravi', 'Neha'] [250, 1200, 75]
Same result as a loop with append, just shorter. Keep it simple: if it needs more than one condition, a normal loop is easier to read.
Practice in Python ✓ Solved
Use one list comprehension to keep only the .csv files from files, then print the result.
Expected output
['a.csv', 'c.csv']
Reference solution
files = ["a.csv", "b.json", "c.csv", "notes.txt"]
csv_files = [f for f in files if f.endswith(".csv")]
print(csv_files)
Question 1 · Easy
What is [x * 2 for x in [1, 2, 3]]?
Question 2 · Medium
What is [x for x in [5, 12, 8] if x > 6]?
Question 3 · Hard
What is [w.upper() for w in ["a", "b"]]?
Key takeaways
[expr for x in list if cond] transforms and filters in one line. Great for cleaning columns.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in