Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

How to Select Items From a List in Python

A list comprehension is the straightforward way to select matching items from a Python list. Learn when to use indices, iterators, and itertools instead.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

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, including 0, False, '', and None. 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, or next() 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.