Skip to content

Module 4 · Operators — topic 13 of 16

Membership operators

in and not in test whether a value appears in a string, list, tuple, set or dictionary. Learn how membership works for each type and why sets and dictionaries are fastest.

Beginner 10 min read·Lesson 56 of 306 in Python Programming

Learning objectives

  • Use in and not in with strings and collections
  • Explain that in on a dictionary checks keys
  • Choose a set for fast repeated membership tests

Definition

in and not in test whether a value appears in a string, list, tuple, set or dictionary. Learn how membership works for each type and why sets and dictionaries are fastest.

Introduction

The membership operators in and not in answer the question “is this value inside that collection?” They return True or False and read almost like English: if "@" in email:.

Why it matters

Checking membership is everywhere: Is this username taken? Does the text contain a banned word? Is this product in stock? in replaces whole loops with a single readable expression.

Detailed explanation

Strings: in checks for a substring: "py" in "python" is True. It is case-sensitive.

Lists and tuples: in checks whether any element is equal to the value, scanning from the start.

Sets: in checks membership using hashing, which stays fast even for millions of items.

Dictionaries: in checks keys, not values: "tea" in {"tea": 20} is True, but 20 in it is False. Use value in d.values() to search values.

not in is the negation: x not in items is clearer than not x in items.

For many repeated checks against a large list, convert it to a set once; each lookup is then much faster.

Membership tests use equality, so 1 in [1.0, 2.0] is True and True in [1, 2] is also True, because True equals 1. With mixed types this can occasionally surprise you; keep collections to one type of value.

in is also what a for loop uses to walk through a collection, but the meaning differs by position: for x in items iterates, while if x in items tests membership.

Syntax

Python
value in collection
value not in collection
key in dictionary
  • Returns True or False.
  • For strings it tests substrings.
  • For dictionaries it tests keys.

Code examples

Strings and lists

Python
print("py" in "python")
print("Py" in "python")
print(3 in [1, 2, 3])
print("kiwi" not in ["apple", "mango"])
Output
True
False
True
True

Dictionaries check keys

Python
stock = {"tea": 20, "coffee": 0}
print("tea" in stock)
print(20 in stock)
print(20 in stock.values())
Output
True
False
True

More examples

Validating a sign-up

Python
taken = {"asha", "ben", "chen"}
banned_words = ["admin", "root"]
def check_username(name):
name = name.lower()
if name in taken:
return "already taken"
if any(word in name for word in banned_words):
return "not allowed"
if " " in name:
return "no spaces, please"
return "available"
for candidate in ["Ben", "superadmin", "dev k", "dev_k"]:
print(candidate, "->", check_username(candidate))
Output
Ben -> already taken
superadmin -> not allowed
dev k -> no spaces, please
dev_k -> available

Step-by-step explanation

  • taken is a set, so each in check is fast regardless of size.
  • Lower-casing first makes the check case-insensitive.
  • word in name checks whether a banned word appears inside the username; any() stops at the first match.
  • " " in name finds spaces in the text.

Expected output

Running “Validating a sign-up” prints exactly:

TextOutput
Ben -> already taken
superadmin -> not allowed
dev k -> no spaces, please
dev_k -> available

Practical applications

  • Sign-up forms check whether an email is already registered.
  • Content filters scan messages for blocked words with in.
  • Inventory systems check whether a product code exists in a dictionary.

Best practices

  • Use sets for large collections you test repeatedly.
  • Normalise case before membership tests on text.
  • Use x in ("a", "b") instead of chains of == or.

Common mistakes

Searching dictionary values with in

Avoid

if 20 in prices:

Prefer

if 20 in prices.values():

in on a dictionary only looks at keys.

Writing not x in y

Avoid

if not item in cart:

Prefer

if item not in cart:

Both work, but not in is the clearer, idiomatic form.

Key takeaways

  • in and not in test membership and return Booleans.
  • Strings test substrings; dictionaries test keys.
  • Sets make membership tests fast.

Try it yourself

  1. 1
    Check whether a typed character is a vowel using in "aeiou".
  2. 2
    Given a list of 5 allowed colours, print whether the user’s choice is allowed, ignoring case.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic