PYTHON

Python in: The List/String Contains Operator in Python

The in operator in Python checks if a specified value exists within a sequence, such as a list, tuple, or string.

In Python, the in keyword also helps iterate over sequences in for loops (link).

How to Use the in Operator in Python

in needs a value to search for and a sequence to search within, returning a boolean. The in operator returns True if the specified value is exists within a sequence. Conversely, the operator returns False if the specified value doesn’t exist.

value in sequence
  • value: The value to search within the sequence.
  • sequence: The list, tuple, string, or other sequence to search.

When to Use the in Operator in Python

The in operator is especially useful for checking membership in collections and substrings in strings.

Checking for Element Presence

You can use the in operator to check if an element exists in a list, string, tuple, or other sequence.

fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits)  # Outputs: True
print('grape' in fruits)  # Outputs: False

Checking If a String Contains a Substring

The in operator is efficient for checking if a substring is present within a string.

sentence = "The quick brown fox"
print("quick" in sentence)  # Outputs: True
print("slow" in sentence)  # Outputs: False

Validating User Input

You can validate user input by checking if the input contains required characters or substrings.

user_input = "hello@domain.com"
if "@" in user_input:
    print("Valid email")  # Outputs: Valid email
else:
    print("Invalid email")

Examples of Using the Python in Operator

Game Item Collection

In a game, you might use the in operator to check if a player has collected a specific item.

inventory = ['sword', 'shield', 'potion']
print('sword' in inventory)  # Outputs: True
print('bow' in inventory)  # Outputs: False

Social Media User Validation

A social media app can use the in operator to check if a username is still available.

registered_users = ['alice', 'bob', 'charlie']
username = 'alice'
if username in registered_users:
    print("Username is taken")  # Outputs: Username is taken
else:
    print("Username is available")

Search Engine Keyword Match

A search engine might use the in operator to check if a keyword is present in a search query.

search_query = "best Python tutorials"
keyword = "Python"
if keyword in search_query:
    print("Keyword found")  # Outputs: Keyword found
else:
    print("Keyword not found")

Learn More About the Python in Operator

Python String contains() Method

Unlike other programming languages, there’s no built-in method like string contains() in Python. Instead, however, you can use the in operator to check if a string contains a substring.

text = "Learning Python is fun"
# No string.contains() method
print("Python" in text)  # Outputs: True
print("Java" in text)    # Outputs: False

Case Sensitivity

Like other string operation in the Python programming language, the in operator is case-sensitive. For case-insensitive checks, you can convert both strings to the same case.

text = "Hello World"
print('hello' in text.lower())  # Outputs: True
print('HELLO' in text.upper())  # Outputs: True

Performance Considerations

The in operator usually offers good performance with most sequences, including large collections.

large_list = list(range(1000000))
print(999999 in large_list)  # Outputs: True

Using in with Dictionaries

You can also use the in operator to check for the presence of keys in a dictionary.

student = {'name': 'Alice', 'age': 24}
print('name' in student)  # Outputs: True
print('address' in student)  # Outputs: False

Complex Conditions

You can combine the in operator with Python logical operators for complex conditions.

permissions = ['read', 'write']
if 'read' in permissions and 'write' in permissions:
    print("User has read and write permissions")  # Outputs: User has read and write permissions
Learn Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH