How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in operator (or in your specific case, not in ). As mentioned in the documentation, The operators in and not in test for membership. x in s evaluates to True if
x is a member of s , and False otherwise. x not in s returns the negation of x in s .
Additionally, The operator not in is defined to have the inverse true value of in .
y not in x is logically the same as not y in x .
Here are a few examples: 'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable): (1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS
defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs. ... in and not in , are supported by types that are iterable or implement the __contains__() method.
For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in short-circuits, so if your element is at the start of the list, in evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options: list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.list.count can be used if you want to count the occurrences.
The XY Problem: Have
you considered sets?Ask yourself these questions: - do you need to check whether an item is in a list more than once?
- Is this check done inside a loop, or a function called repeatedly?
- Are the items you're storing on your list hashable? IOW, can you call
hash on them?
If you answered "yes" to these questions, you should be using a set instead. An in membership test on list s is O(n) time complexity. This means that python has to
do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead. set objects, on the other hand, hash their values for constant time membership check. The check is also done using in :
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end.
This is evident from the timings below: l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__ . - HowTo
- Python How-To's
- Check Element Not in a List in Python
Created: February-07, 2021 | Updated: February-28, 2021
- Use
not in to Check if an Element Is Not in a List in Python - Use the
__contains__ Method of the List to Check if an Element Is Not in a List
in Python
In this tutorial, we will introduce how to check if an element is not in a list in Python. Use not in to Check if an Element Is Not in a List in PythonThe in keyword in Python can be used to check whether an element is present in a collection or not. If an element is present, then it returns True ; otherwise, it returns False . For
example:
x = 3 in [1,2,5]
y = 1 in [1,2,5]
print(x)
print(y)
Output: False
True
If we need to check if an element is not in the list, we can use the not in keyword. The not is a logical operator to converts True to False and vice-versa. So if an element is not present in a list, it will return True . x = 3 not in [1,2,5]
print(x)
Output: True
Use the __contains__ Method of the List to Check if an Element Is Not in a List in PythonIn Python, we have magic functions that are associated with classes and are not to be meant invoked directly although it is possible. One such function called __contains__ can be used to check if an element is present in a list or not. For example, x = [1,2,5].__contains__(1)
print(x)
x = [1,2,5].__contains__(3)
print(x)
Output: True
False
Although this method works, it is not
advisable to use this method since magic functions are not intended to be invoked directly. Related Article - Python ListConvert a Dictionary to a List in PythonRemove All the Occurrences of an Element From a List in PythonRemove Duplicates From List in PythonGet the Average of a List in Python
How do you check if a variable is in a list Python?
Check if Variable is a List with type() Now, to alter code flow programatically, based on the results of this function: a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")
How do I check if an item is in a list B list in Python?
Using “in” Operator
In this example, we are using 'in' operator to check if an item or element exists in a sequence or not. If an item exists in the list, it will return the output is true, else it returns false. Explanation: In the above example, we used the 'in' operator to check whether 'b' exists in MyList or not.
|