Filtering a List by Condition in Python
Filtering a List by Condition in Python
Filtering is one of the most common patterns in Python. You use it whenever you need to narrow down data — selecting valid items, removing noise, or preparing a clean list for the next step in your pipeline. It’s simple, powerful, and shows up in nearly every real‑world script.
Source Code
nums = [3, 10, 7, 2, 8]
filtered = [n for n in nums if n > 5]
# pseudocode:
# for each n in nums:
# if n is greater than 5:
# include n in the new list
-
Iteration
— walks through each number in
nums. -
Condition
— checks whether
n > 5. - Selection — keeps only values that pass the test.
- Result — produces a new list with only the matching items.
Expected Output
# expected output
# before: [3, 10, 7, 2, 8]
# after: [10, 7, 8]
Filtering is a building‑block skill: once you understand this pattern, you can apply it to data cleaning, validation, transformation, and even more advanced list comprehensions.