In Python, there is no direct equivalent to xs.contains(item) when working with lists. Instead, programmers rely on a syntactically elegant approach that leverages membership testing operators.
To determine if an element item is present in a list xs, use the following construction:
<code class="python">if my_item in some_list: # Item is present in the list else: # Item is not present in the list</code>
This approach also allows for the inverse operation, checking if an element is absent:
<code class="python">if my_item not in some_list: # Item is not present in the list else: # Item is present in the list</code>
While convenient, it's important to note that membership testing in lists and tuples has an O(n) time complexity, where n is the length of the collection. This means that iterating through the elements of the list is required to determine presence or absence.
In contrast, membership testing in sets and dictionaries operates with O(1) complexity, meaning that it can directly retrieve elements without iterating. This makes sets and dictionaries efficient options when rapid lookups are required.
The above is the detailed content of Is There a Built-in `contains` Function for Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!