if not in list Python
To check if a value is not in a list in Python, we can write an if
statement using a not in
expression like this:
items = [1, 2, 3]
if 4 not in items:
print(True)
True
In the above example, 4 is not in the list items so True
is returned.
The opposite of the above is to use an in expression with an if-else
statement like this:
items = [1, 2, 3]
if 4 in items:
print('In list.')
else:
print('Not in list.')
Not in list.
If the value is not in the list, then the code inside the else part of the statement will execute.
Check if Tuple is not in a List of Tuples in Python
The not in expression also works when evaluating whether a tuple is in a list of tuples like this:
items = [(2, 1), (1, 2), (3, 4)]
if (3, 4) not in items:
print('No tuple match.')
else:
print('Match found.')
Match found.