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
Release: 2024-10-30 09:16:27
Original
517 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template