Membership Operators
Nerd Cafe
What Are Membership Operators in Python?
Python provides two membership operators to test whether a value is in a sequence (like a list, string, tuple, etc.) or not:
in
Returns True
if present
"cat" in "category"
not in
Returns True
if not present
"dog" not in "cat"
Step-by-Step Usage
1. Using in
with Lists
in
with ListsML Tip: Useful when selecting features dynamically from a dataset.
2. Using not in
with Lists
not in
with ListsML Tip: Before tuning, check if a parameter is valid for your model.
3. Using with Strings
NLP Example: You might want to detect keywords in a sentence.
4. Using with Tuples
Practical ML Tip: Use this in model evaluation settings.
5. Using with Dictionaries (Only Keys are Checked)
Tip: in
only checks keys in a dictionary, not values.
ML Utility Summary
Feature selection
in
if 'age' in df.columns:
Parameter check
in
, not in
'max_depth' in model_params
Word/keyword search in NLP
in
'data' in sentence
Model metric validation
in
'accuracy' in metrics_list
Keywords
python
, membership operators
, in
, not in
, list
, string
, tuple
, dictionary
, data preprocessing
, feature selection
, machine learning
, model parameters
, pandas
, dataframe
, NLP
, keyword search
, boolean logic
, conditional checks
, data validation
, error handling
, nerd cafe
Last updated