Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteUse a list comprehension to create a new list containing only the items that meet a condition. For example, [number for number in numbers if number % 2 == 0] selects the even numbers. The expression before for determines what goes into the result; the if clause determines which input items are included.
Use a list comprehension to filter a list
The general pattern is [expression for item in iterable if condition]. The condition is checked for each item, and matching items are added to a new list in their original order.
numbers = [1, 2, 3, 4, 5, 6]
evens = [number for number in numbers if number % 2 == 0]
print(evens) # [2, 4, 6]
This is the clearest default when you need a concrete list of the values that match a rule. Python’s list-comprehension tutorial covers this syntax.
Transform items while selecting them
The expression before for can produce a changed value, while the if clause still decides whether the input item is included.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
words = ["python", "", "list"]
uppercase_words = [word.upper() for word in words if word]
print(uppercase_words) # ['PYTHON', 'LIST']
Here, nonempty words are selected and converted to uppercase. This is different from a conditional expression, which chooses an output for each item rather than excluding items:
labels = [word.upper() if word else "(empty)" for word in words]
print(labels) # ['PYTHON', '(empty)', 'LIST']
Use the filtering form when some inputs should be omitted; use a conditional expression when every input should produce an output.
Rank #2
Filter records by a field
For dictionaries or tuples, put the field test in the condition. The expression can keep the complete record or return just one of its fields.
users = [
{"name": "Ari", "status": "active"},
{"name": "Bo", "status": "inactive"},
]
active_users = [user for user in users if user["status"] == "active"]
rows = [("Ari", "active"), ("Bo", "inactive")]
active_rows = [row for row in rows if row[1] == "active"]
operator.itemgetter() can provide a reusable field accessor where an operation accepts a key function, but it only retrieves a field; it does not select or filter records by itself. See the operator.itemgetter documentation.
Keep each matching item’s index
Use enumerate() when the position is part of the result. Its default index starts at zero.
items = ["pear", "plum", "peach"]
selected = [(i, item) for i, item in enumerate(items) if item.startswith("p")]
print(selected) # [(1, 'plum'), (2, 'peach')]
The loop receives both the index and value, so the condition can use either or both.
Use filter() or a generator when you do not need a list immediately
filter(predicate, iterable) returns an iterator in current Python. Wrap it in list() if the next step requires a list. A generator expression is another iterator-based option.
def is_even(number):
return number % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
filtered = filter(is_even, numbers)
print(list(filtered)) # [2, 4, 6]
generated = (number for number in numbers if number % 2 == 0)
print(list(generated)) # [2, 4, 6]
These iterators produce values as they are consumed. If you convert one to a list, that list contains the produced values; consuming an iterator also advances it. For a short inline condition and a list result, a comprehension is usually easier to read. The Python Functional Programming HOWTO describes filter() as returning an iterator and notes that list comprehensions can achieve the same filtering effect.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchBest Value
Select items that fail a condition or match separate selectors
The standard-library itertools module provides helpers for two distinct cases:
itertools.filterfalse(predicate, items)yields items for which the predicate is false.itertools.compress(data, selectors)yields each data item whose corresponding selector is truthy.
from itertools import compress, filterfalse
numbers = [1, 2, 3, 4, 5, 6]
not_even = list(filterfalse(is_even, numbers))
names = ["Ari", "Bo", "Cam"]
selected_names = list(compress(names, [True, False, True]))
print(not_even) # [1, 3, 5]
print(selected_names) # ['Ari', 'Cam']
These functions return iterators, so use list() when a materialized list is needed. compress() is useful when selection comes from a separate sequence of aligned selectors. See the filterfalse and compress documentation.
Quick Recap
Avoid common filtering mistakes
- Do not remove items from the list you are iterating over. Build a new list with a comprehension instead, so iteration is not disrupted by changes to the input.
- Be precise with truthiness.
[x for x in items if x]excludes every falsey value, including0,False,'', andNone. If only one value should be excluded, write that comparison explicitly, such as[x for x in items if x is not None]. - Do not use a set just to filter. A comprehension preserves input order and duplicate values.
- Use a different pattern to find only the first match. A comprehension builds every match. Use a loop with
break, ornext()on a generator expression, when you need only the first matching item.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




