Lists
How to check if an item is in a list in Python
Quick answer
Use the `in` operator to check if an item is in a list, e.g. `item in my_list`
my_list = [1, 2, 3]
item = 2
if item in my_list:
print(f'{item} is in the list')This snippet checks if an item is present in a list using the `in` operator. This approach is efficient because it uses a linear search algorithm with a time complexity of O(n), where n is the number of elements in the list. However, for large lists, using a set for membership testing can be more efficient.
Variations
Alternate approach
my_list = [1, 2, 3]
item = 2
print(item in my_list)more concise
Edge case
my_list = [1, 2, 3]
item = None
if item in my_list:
print('Item is in the list')handle None values
Related pattern
my_set = {1, 2, 3}
item = 2
if item in my_set:
print('Item is in the set')use a set for faster lookup
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.