Skip to content

Python contains() function

  • by

There is no built-in contains() function in Python. But you can check if a value is present in a sequence (such as a list, tuple, string, or set) using the in keyword. Here’s how you can use it:

element in sequence

Here’s how you can use the in keyword to check for containment:

List:

my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print("3 is present in the list")

Sstring:

my_string = "Hello, World!"
if "o" in my_string:
    print("The letter 'o' is present in the string")

Dictionary (applies to keys, not values):

my_dict = {"name": "John", "age": 30, "city": "New York"}
if "age" in my_dict:
    print("The key 'age' is present in the dictionary")

Set:

my_set = {1, 2, 3, 4, 5}
if 6 in my_set:
    print("6 is present in the set")

Remember to use the in keyword with the appropriate data type based on the data structure you are working with.

Python contains() function example

Let’s create a function called contains() that checks if an element exists in a given sequence:

def contains(sequence, element):
    return element in sequence

# Example usage
my_list = [1, 2, 3, 4, 5]
if contains(my_list, 3):
    print("3 is present in the list")

my_string = "Hello, World!"
if contains(my_string, "o"):
    print("The letter 'o' is present in the string")

my_dict = {"name": "John", "age": 30, "city": "New York"}
if contains(my_dict, "age"):
    print("The key 'age' is present in the dictionary")

my_set = {1, 2, 3, 4, 5}
if contains(my_set, 6):
    print("6 is present in the set")

Output:

Python contains() function

In this example, the contains() function takes two arguments: sequence and element. It checks if element is present in the given sequence using the in keyword and returns True if it exists, and False otherwise. This way, you can achieve a similar behavior to a hypothetical contains() function.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading