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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 10 views 0 copies

Python code

11 lines
Python 3.9+
ages = [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

stdout
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

  1. Use a list comprehension: `adults = [age for age in ages if age >= threshold]`.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.