Python
Programming
List Operations
Conditional Statements
Code Tutorials

How to check if one of the following items is in a list?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

A common task in Python is checking whether any item from a group of candidates exists in a list. For example, you might want to know if a user has any of several required permissions, or if a shopping cart contains any items from a promotional category. This article covers multiple approaches, from the most Pythonic to performance-optimized techniques for large datasets.

The Simple Case: Checking for a Single Item

Before checking for multiple items, here is how you check for a single item using Python's in operator:

python
1fruits = ["apple", "banana", "cherry", "date"]
2
3if "banana" in fruits:
4    print("Found banana!")

The in operator performs a linear scan through the list. For a single lookup, this is clean and readable.

Checking if Any of Several Items Is in a List

Method 1: Using any() with a Generator Expression

The most Pythonic way to check if at least one item from a group exists in a list is to use any():

python
1fruits = ["apple", "banana", "cherry", "date"]
2targets = ["mango", "banana", "kiwi"]
3
4if any(item in fruits for item in targets):
5    print("At least one target fruit is in the list")

any() short-circuits, meaning it stops as soon as it finds the first True value. If "banana" is the second item checked, it returns True immediately without checking "kiwi".

Method 2: Using Set Intersection

Converting one or both collections to sets gives you access to set intersection, which is faster for larger datasets:

python
1fruits = ["apple", "banana", "cherry", "date"]
2targets = ["mango", "banana", "kiwi"]
3
4if set(targets) & set(fruits):
5    print("There is overlap between the two collections")

The & operator returns a set of common elements. Since a non-empty set is truthy in Python, this works directly in an if statement. You can also use the .intersection() method:

python
if set(targets).intersection(fruits):
    print("Found a match")

Method 3: Using not set.isdisjoint()

The isdisjoint() method returns True if two sets have no elements in common. Negating it tells you whether there is any overlap:

python
1fruits_set = set(fruits)
2targets_set = set(targets)
3
4if not fruits_set.isdisjoint(targets_set):
5    print("At least one common element exists")

This approach is efficient because isdisjoint() also short-circuits internally. It stops checking as soon as it finds a common element.

Finding Which Items Matched

Sometimes you need to know not just whether a match exists, but which items matched:

python
1fruits = ["apple", "banana", "cherry", "date"]
2targets = ["mango", "banana", "kiwi", "cherry"]
3
4matched = [item for item in targets if item in fruits]
5print(matched)  # ["banana", "cherry"]

For better performance with large lists, convert fruits to a set first:

python
fruits_set = set(fruits)
matched = [item for item in targets if item in fruits_set]

Set membership checks run in O(1) average time compared to O(n) for list membership, making this significantly faster when fruits is large.

Performance Comparison

The choice of method matters when you are working with large collections. Here is how the approaches compare:

python
1import timeit
2
3fruits = list(range(10000))
4targets = [9999, 10001, 10002]  # only first item matches
5
6# Method 1: any() with list
7timeit.timeit(lambda: any(t in fruits for t in targets), number=1000)
8# Slower: linear scan for each target
9
10# Method 2: set intersection
11fruits_set = set(fruits)
12timeit.timeit(lambda: bool(set(targets) & fruits_set), number=1000)
13# Faster: O(1) lookups
14
15# Method 3: isdisjoint
16timeit.timeit(lambda: not fruits_set.isdisjoint(targets), number=1000)
17# Fastest: short-circuits with O(1) lookups

For small lists (under a few dozen items), all methods are effectively instant and you should pick whichever reads most clearly. For lists with thousands of items, converting to a set first and using isdisjoint() or set intersection gives the best performance.

Checking Across Different Data Types

These techniques work with any hashable types, not just strings:

python
1# Integers
2error_codes = [400, 401, 403, 404, 500]
3critical = [500, 502, 503]
4
5if set(error_codes) & set(critical):
6    print("Critical error detected")
7
8# Tuples
9coordinates = [(0, 0), (1, 2), (3, 4)]
10check_points = [(1, 2), (5, 5)]
11
12if any(point in coordinates for point in check_points):
13    print("Found a matching coordinate")

Common Pitfalls

  • Using or incorrectly: Writing if "a" or "b" in my_list does not check for both items. It evaluates as if ("a") or ("b" in my_list) because "a" is always truthy. You must write if "a" in my_list or "b" in my_list.
  • Forgetting that sets require hashable elements: Lists, dicts, and other mutable types cannot be added to sets. If your items are unhashable, stick with any() and list-based checks.
  • Repeated set conversion: If you check membership multiple times against the same list, convert it to a set once and reuse the set rather than converting on every check.
  • Case sensitivity with strings: "Apple" and "apple" are different items. Normalize case before checking if case-insensitive matching is needed.

Summary

For checking if any of several items exists in a list, use any(item in my_list for item in targets) for readability or convert to sets and use intersection or isdisjoint() for performance. For small lists, any method works. For large datasets, sets provide O(1) lookups that make a meaningful difference. Always be careful with the or operator, as it does not distribute across in checks the way natural language suggests.


Course illustration
Course illustration

All Rights Reserved.