Pythonic Way to Verify Presence of an Item in a List
This tutorial provides you with the best way of checking if an element exists within a list, or list-like collection. The pythonic way for doing so is via using ‘in’ keyword, which will return either …
This tutorial provides you with the best way of checking if an element exists within a list, or list-like collection. The pythonic way for doing so is via using ‘in’ keyword, which will return either True or False depending on whether it finds the element in the list or not.
Python’s ‘in’ operator allows you to determine if an item exists within a list. Here’s how you can do it:
my_list = [1, 2, 3, 4, 5]
if 2 in my_list:
print("The element is present.")
else:
print("The element is not present.")
When the value of ‘in’ operator is evaluated to be True, it means that the item does exist within your list. If it’s False, then the item doesn’t exist in the list.
You can also use multiple items for a single check:
my_list = [1, 2, 3, 4, 5]
if 2 in my_list and 7 not in my_list:
print("Both elements are present.")
else:
print("An element is missing.")
In the above example, if both elements exist within list then it will print “Both elements are present”. But, if either of them does not exist in the list then it prints “An element is missing”.
It’s important to remember that ‘in’ operator compares values but not types. If you’re checking whether a string or an integer exists within your list and they have the same value, but different type, the ‘in’ will still return True because it only checks for values, not data types.
Here is another example where we are checking if a specific item is in a list:
my_list = [1, 2, "two", 4, "four"]
if "two" in my_list:
print("The element 'two' is present.")
else:
print("The element 'two' is not present.")