Home >Backend Development >Python Tutorial >Is There a Built-in \'Contains\' Function for Lists in Python?

Is There a Built-in \'Contains\' Function for Lists in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 09:16:27518browse

Is There a Built-in

Does Python Have a Built-in "Contains" Function for Lists?

When working with lists in Python, it's often necessary to check if a particular value exists within the list. For instance, can we determine if [1, 2, 3] contains 2 efficiently?

Solution: Using the "in" Operator

Python provides a concise and efficient way to check for list membership using the in operator. This operator evaluates to True if the specified value exists in the list and False otherwise.

To use the in operator:

<code class="python">if my_item in some_list:
    # Actions to perform if my_item is in some_list</code>

Example:

<code class="python">some_list = [1, 2, 3]

if 2 in some_list:
    print("2 is in the list.")
else:
    print("2 is not in the list.")</code>

Inverses: Checking for Absence

The not in operator can be used to check if a value is not present in a list:

<code class="python">if my_item not in some_list:
    # Actions to perform if my_item is not in some_list</code>

Performance Considerations

The in operation has an O(n) complexity for lists and tuples, where n is the number of elements in the collection. However, for sets and dictionaries, the in operation has an O(1) complexity, indicating much faster lookup times.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn