smartyfy.mrindigi.com

Python Master Course V2 — 015. Membership and Identity Operators

SMARTYFY · PYTHON MASTER COURSE V2 · MODULE 02 · LESSON 015/200

Membership and Identity Operators

Estimated study: 60–90 minutes. Prerequisite: Lesson 014

in, not in, is, is not and equality versus identity.

Video lesson

Video not yet available.

Learning objectives

Explain in, not in, is, is not and equality versus identity, trace control flow, identify boundary cases, debug errors and implement a real-world decision-making project.

Prerequisites: Python 3.10+, variables, types, comparison expressions, and prior course lessons.

Understand and apply: Membership and Identity Operators

Choose the question you mean to ask

Membership, equality, and identity answer different questions. item in collection asks whether the collection contains a matching item. a == b asks whether two values compare equal. a is b asks whether both names refer to exactly the same object. An identity test does not compare all the contents, and an equality test does not promise that two names share storage. Most business-value comparisons need ==, not is.

For strings, membership means substring matching: "py" in "python" is True, but "Py" in "python" is False. The comparison is case-sensitive, and the substring must be contiguous. For lists and tuples, membership checks elements rather than substrings of every element. Thus "py" in ["python"] is False. not in negates the membership result and is usually clearer than wrapping the whole expression in not.

Keys and values are different searches

prices = {"pen": 10, "book": 40}
print("pen" in prices)
print(10 in prices)
print(10 in prices.values())
print("bag" not in prices)

Expected output:

True
False
True
True

A dictionary maps keys to values. Iterating or testing membership directly on a dictionary uses its keys; call .values() when you deliberately want to search the values. Testing a key before bracket lookup can prevent a missing-key error. Do not first read prices["bag"] and only then ask whether the key exists: the lookup would already have failed. Sets are useful for representing allowed names without duplicates; their broader behavior is developed later in the course.

Equal lists can still be independent objects

Trace an alias and a separate list

first = [1, 2]
second = [1, 2]
alias = first
print(first == second)
print(first is second)
print(first is alias)
alias.append(3)
print(first)
print(second)

Expected output:

True
False
True
[1, 2, 3]
[1, 2]

The two list displays create separate objects with equal contents. Assignment to alias does not create a third list; it binds another name to the first list. Appending through that alias changes the object seen through first. The independent second list remains unchanged. This distinction becomes essential when later lessons copy or mutate collections.

Use value is None or value is not None to test the dedicated absence marker. An empty list, zero, and an empty string are values distinct from None, even though all are falsey. Avoid identity tests for numbers and strings. Python may reuse some immutable objects internally; observed identity in a small example is not a reliable equality rule.

Make an access decision consistently Boolean

For the role-permission example, define a narrow classroom contract: the role is a string, permissions maps role strings to collections of permission strings, and the answer is always True or False. Check that the role exists before looking up its permissions. An unknown role must return False, not a message such as "Unknown". That message is nonempty and therefore truthy, so a caller using it as a condition could take the allowed branch.

Test an administrator with publish permission, an editor without it, an unknown role, and a known role whose permission collection is empty. The expected results are True, False, False, and False. Keep explanatory status messages separate from an allow/deny Boolean. This example teaches a safe return contract; real authorization still belongs in a trusted application layer with authenticated roles.

Runnable examples

Save each example in a separate lesson_015.py file and run with python lesson_015.py. These are expected outputs, not claims of execution in the browser.

Example 1: Membership

allowed={"admin","editor"}
print("admin" in allowed)
print("guest" not in allowed)

Expected output:

True
True

Example 2: Identity

a=[1,2]
b=[1,2]
print(a==b)
print(a is b)

Expected output:

True
False

Guided project: role-permission checker

This practical exercise turns a small set of business rules into predictable results. Read each branch, predict the result, then run the test cases. Modify one rule and add tests for its boundaries.

Input contract: Roles are strings, and rules map each role to permission strings. The access result is always Boolean; unknown roles are denied.

def access(role,permissions):
 if role not in permissions:
  return False
 return "publish" in permissions[role]
rules={"admin":{"publish","edit"},"editor":{"edit"}}
for role in ["admin","editor","guest"]:
 print(access(role,rules))

Expected output:

True
False
False

Testing: Check ordinary accepted cases, rejected cases, exact thresholds, and malformed inputs. The sample focuses on the lesson’s branching concepts; a production system must additionally validate external inputs and enforce permissions server-side.

Common mistakes and best practices

  • Failing to check invalid values before decision logic.
  • Misunderstanding branch ordering and short-circuit behavior.
  • Using overly complex nested expressions instead of readable predicates.
  • Not testing equality at inclusive thresholds.
  • Confusing illustrative classroom policies with real-world requirements.

Practice and reason it through

Attempt each question before opening its answer. Write down the result and the reason, then compare your reasoning with the worked solution.

1. Does dictionary membership search its values?

record = {"score": 90}
print("score" in record)
print(90 in record)
Reveal answer and explanation

The output is True then False. Bare dictionary membership tests keys, and "score" is a key while 90 is only a value. 90 in record.values() would be True.

Expected output:

True
False

2. Which names identify the same list?

a = [5]
b = [5]
c = a
print(a == b, a is b, a is c)
Reveal answer and explanation

b is a new list with equal contents; c is another name for the object referenced by a. Equality is True for a and b, identity is False for a and b, and identity is True for a and c.

Expected output:

True False True

3. Why is the unknown-role result unsafe in an if condition?

Reveal answer and explanation

A nonempty string is truthy. Returning "Unknown" therefore does not mean denied to a caller using if access(...). Return False for unknown roles and keep all return values Boolean. The guard also prevents indexing a missing key.

def access(role, permissions):
    if role not in permissions:
        return False
    return "publish" in permissions[role]

rules = {"admin": {"publish", "edit"}, "editor": {"edit"}}
print(access("admin", rules))
print(access("editor", rules))
print(access("guest", rules))

Expected output:

True
False
False

4. How can you distinguish an absent result from an empty result?

result = []
print(result is None)
print(not result)
Reveal answer and explanation

Use result is None. A result of [] is an existing, empty collection; None is the absence marker. if not result combines those cases, which is only suitable when the policy deliberately treats them the same.

Expected output:

False
True

5. Why does a substring test differ from a list membership test?

print("py" in "python")
print("py" in ["python"])
Reveal answer and explanation

The first is True because "py" is a contiguous substring of "python". The second is False because the list has one complete element, "python", which is unequal to "py". To ask whether any element contains a substring, a later iteration lesson will examine the elements one by one.

Expected output:

True
False

Further challenge

  • Challenge: extend the project with a new policy and document three tests including one boundary case.

Mastery checkpoint

Demonstrate that you can predict the examples, explain branch order, run the project, and write at least three additional tests. Summary: in, not in, is, is not and equality versus identity require explicit reasoning, validation, and reproducible testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.