How to Filter a List in Python with a Loop
Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.
Python code
11 linesages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18
adults = []
for age in ages:
if age >= threshold:
adults.append(age)
print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
Output
All ages: [34, 12, 45, 8, 67, 21, 18, 55, 3]
Adults (18+): [34, 45, 67, 21, 18, 55]
Count of adults: 6
How it works
A for loop iterates over each item in the ages list. The if condition checks whether the current age is at least the threshold. When true, append adds the value to the new adults list. Using a separate list keeps the original data unchanged, which is safer for later steps. The len() function then counts how many items met the condition.
Common mistakes
- Modifying the original list while iterating over it, which can skip items or cause errors.
- Forgetting to initialize `adults = []` before the loop, leading to a NameError.
- Using `>` instead of `>=` so the threshold value itself is excluded.
Variations
- Use a list comprehension: `adults = [age for age in ages if age >= threshold]`.
- Use the `filter` built-in: `adults = list(filter(lambda age: age >= threshold, ages))`.
Real-world use cases
- Filtering user records where age meets a minimum sign-up requirement before sending onboarding emails.
- Selecting orders above a price threshold from a sales feed to route them to a special review queue.
- Picking log entries with severity level above a cutoff to forward to an alerting system.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.