To check if a value is in a list using Python, the easiest way is with the in operator.
value = 1
l = [0, 1, 2, 3, 4]
if value in l:
print("value is in list")
else:
print("value is not in list")
#Output:
value is in list
When working with collections of data in Python, the ability to perform certain checks of different conditions is valuable.
One such case is if you want to check if a value is in a list in Python.
To check if a value is in a list using Python, the easiest way is with the in operator.
If the value you want to check is in the list, then in returns True.
Otherwise in returns False.
Below shows you a simple example of how you can check if a value is in a list using Python.
value = 1
l = [0, 1, 2, 3, 4]
if value in l:
print("value is in list")
else:
print("value is not in list")
#Output:
value is in list
How to Check if Value is Not in List in Python
To check if a value is not in a list using Python, you can use the in operator combined with the not operator.
Just put not in front of in to negate the returned value from in.
Below shows you a simple example of how you can check if a value is not in a list using Python.
value = 5
l = [0, 1, 2, 3, 4]
if value not in l:
print("value is not in list")
else:
print("value is in list")
#Output:
value is not in list
Hopefully this article has been useful for you to learn how to check if a value is in a list using Python.