How to check if an element exists in a Python list
To check if an element, string or value is in a list in Python, use the operator in or not in.
x in namelist
The x parameter is a string or value to search for and namelist is the name of the list.
The answer is True if the element is present in the list. It is False if it is not present.
x not in namelist
In this case the answer is True if the element is not present in the list. It is False if it is present.
Note. In both cases, the search is case sensitive. Lowercase letters are distinct from uppercase. For example, the strings "Abc" and "abc" are different. Furthermore, if the element exists in the list, the position of the element in the list is not indicated but only the boolean result True.
Examples
Example 1
Create a list with some elements.
>>> city=['London', 'Paris', 'Rome']
Check if the string 'Rome' exists in the list.
>>> 'Rome' in city
True
The string exists in the list. The result is True.
Example 2
Check if the string 'Berlin' exists in the above list.
>>> 'Berlin' in city
False
The string does not exist in the list. The result is False.