- Aliases
- and operator
- Arrays
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Filter()
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Property()
- Random module
- range() function
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
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).
Quick Answer: How to Use the in
Operator in Python
The in
operator in Python is a membership operator used to check if a value is present in a sequence (like a list or string). It returns a boolean value: True
if the value is found, and False
otherwise. You can also use not in
to check if a value is absent.
Syntax:value in sequence
1. Checking a List:
fruits = ['apple', 'banana', 'cherry']
# Check if 'banana' is in the list
print('banana' in fruits)
# Outputs: True
# Check if 'grape' is NOT in the list
print('grape' not in fruits)
# Outputs: True
2. Checking a String (for a substring):
sentence = "hello world"
# Check if 'world' is a substring
print('world' in sentence)
# Outputs: True
The in
operator is commonly used in if
statements to control program flow based on whether an item exists in a collection.
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
Key Takeaways for the Python in
Operator
- It's a Membership Test: The primary purpose of
in
is to check if a value exists within a sequence. It always returnsTrue
orFalse
. - Use
not in
for Absence: To check if a value does not exist in a sequence, use thenot in
operator. - Checks Keys in Dictionaries: When used with a dictionary, the
in
operator checks for the presence of a key, not a value. - It's Case-Sensitive: When checking strings,
'a' in 'Apple'
will beFalse
. You must convert both sides to the same case (e.g.,.lower()
) for a case-insensitive check. - Used in
for
Loops: Thein
keyword is also used to iterate over a sequence in afor
loop (e.g.,for item in my_list:
), which is a separate but related usage.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.