Introduction
In this lesson you will deepen your understanding of Python by working with three powerful operator families that control how variables are updated and how objects are compared and searched:
- Augmented assignment operators (like
+=,-=,*=,/=) for concise value updates - Identity operators (
is,is not) and how they differ from equality (==) - Membership operators (
in,not in) for checking whether values exist inside containers
You will also learn to avoid subtle bugs that come from confusing assignment, identity, equality, and membership in real code.
1. Assignment and Augmented Assignment Operators
You already know the basic assignment operator =. Python also provides augmented assignment operators that update variables in place, making code shorter and often clearer.
1.1 Basic vs augmented assignment
# Basic assignment and update
count = 0
count = count + 5
# Equivalent using augmented assignment
count2 = 0
count2 += 5
print("count =", count)
print("count2 =", count2)
# Output
count = 5
count2 = 5
Explanation:
count = count + 5andcount2 += 5do the same thing: they read the current value and store the updated value back.- Augmented assignment is commonly used in loops, accumulators, and counters.
1.2 Common augmented assignment operators
x = 10
x += 3 # x = x + 3 → 13
x -= 2 # x = x - 2 → 11
x *= 4 # x = x * 4 → 44
x /= 2 # x = x / 2 → 22.0 (note: becomes float)
print(x)
# Output
22.0
Key points:
/=follows normal division rules, so the result is usually a float.- Other augmented operators exist (
//=,%=,**=,&=,|=, etc.) and work similarly.
1.3 Augmented assignment with mutable objects
Augmented assignment can behave differently depending on whether the object is mutable.
nums = [1, 2]
# Augmented assignment on a list
nums += [3, 4]
print(nums)
# Output
[1, 2, 3, 4]
Explanation:
- For lists,
+=extends the existing list (modifies it in place) rather than creating a new one. - This in-place behavior matters for identity, as you’ll see next.
2. Identity vs Equality in Python
Python has two different concepts for comparing things:
- Equality (
==,!=) — compares values - Identity (
is,is not) — compares object identity (whether two variables point to the exact same object in memory)
2.1 Equality vs identity basics
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # same contents?
print(a is b) # same object?
print(a is c) # same object?
# Output
True
False
True
Explanation:
aandbhave equal values ([1, 2, 3]), soa == bisTrue.- They are two different list objects, so
a is bisFalse. cwas assigned directly toa, socandapoint to the same object;a is cisTrue.
2.2 Identity with small integers and strings
CPython (the main Python implementation) interns some immutable objects (like small integers and some strings) for efficiency. This can make identity comparisons look surprising.
x = 10
y = 10
print(x == y) # same value
print(x is y) # often True for small ints
s1 = "hello"
s2 = "hello"
print(s1 == s2)
print(s1 is s2) # may be True due to interning
# Possible Output (typical CPython)
True
True
True
True
Important:
- You must never rely on
isfor comparing numbers or strings. - That
x is yhappens to beTruehere is an implementation detail, not a language guarantee. - Always use
==for value comparison.
2.3 Identity and mutability
With mutable objects, identity is more visible because mutations affect all references to the same object.
nums1 = [1, 2]
nums2 = nums1 # both refer to the same list
nums1.append(3)
print(nums1)
print(nums2)
print(nums1 is nums2)
# Output
[1, 2, 3]
[1, 2, 3]
True
Explanation:
nums2is just another name for the same list asnums1.- Modifying
nums1also changes what you see throughnums2. iscorrectly reports that they are the same object.
2.4 Correct uses of is
Use is only when you explicitly care about object identity, most commonly with singletons like None:
value = None
if value is None:
print("No value provided")
# Output
No value provided
3. Membership Operators: in and not in
Membership operators check whether a value appears inside another object, such as a list, string, tuple, set, or dictionary.
3.1 Membership in lists and strings
fruits = ["apple", "banana", "cherry"]
text = "python programming"
print("banana" in fruits)
print("pear" not in fruits)
print("python" in text)
print("thon" in text)
# Output
True
True
True
True
Explanation:
- For lists,
inchecks if an element is present. - For strings,
inchecks if a substring occurs anywhere inside.
3.2 Membership in dictionaries
For dictionaries, in checks keys, not values.
user = {
"username": "alice",
"age": 30,
"active": True,
}
print("username" in user) # key membership
print("alice" in user) # values are NOT checked by default
print("alice" in user.values()) # explicit value check
# Output
True
False
True
Explanation:
"username" in userisTruebecause"username"is a key.- To search values, use
.values()or.items()explicitly.
3.3 Practical example: login and permissions
allowed_users = ["alice", "bob", "carol"]
username = "bob"
if username in allowed_users:
print("Access granted for", username)
else:
print("Access denied")
# Output
Access granted for bob
Explanation:
- Membership gives a clean way to express set-like checks: “is this user in the allowed list?”
4. Avoiding Common Operator Bugs
Misusing assignment, identity, equality, and membership leads to subtle, hard-to-find bugs. Here are patterns to watch for.
4.1 Confusing = and ==
# Incorrect (and invalid syntax in Python)
# if x = 5: # This will raise a SyntaxError
# ...
# Correct
x = 5
if x == 5:
print("x is five")
# Output
x is five
Use = only for assignment, == for comparison.
4.2 Using is instead of ==
score = 100
# Wrong style: may behave inconsistently across implementations
if score is 100:
print("Perfect score (using is)")
# Correct
if score == 100:
print("Perfect score (using ==)")
# Possible Output
Perfect score (using is)
Perfect score (using ==)
Explanation:
- Even if both branches run here, only the
==check is reliable and portable.
4.3 Misunderstanding dictionary membership
settings = {"theme": "dark", "debug": False}
# Buggy intention: check if debug mode is set to False
if False in settings:
print("Debug explicitly disabled")
else:
print("Checking value correctly...")
if settings.get("debug") is False:
print("Debug explicitly disabled (correct check)")
# Output
Checking value correctly...
Debug explicitly disabled (correct check)
Explanation:
False in settingschecks forFalseas a key, not as a value.- Use
settings.get("debug")(orsettings["debug"]) and then compare the value.
Summary / Key Takeaways
In this lesson on Assignment, Identity, and Membership Operators, you have learned:
- Augmented assignment operators (
+=,-=,*=,/=) provide a concise way to update variables while often preserving object identity for mutable types. - Equality (
==) compares values, whereas identity (is) compares whether two variables reference the exact same object in memory. - Identity comparisons can appear surprising with small integers and interned strings, so
ismust not be used as a replacement for==when checking values. - Mutable objects highlight identity clearly because changes through one reference are visible through all references to the same object.
- Membership operators (
in,not in) check containment in sequences and collections, and operate on list elements and string substrings. - For dictionaries,
inchecks for keys by default, requiring explicit use of.values()or.items()to test values or key–value pairs. - Common bugs arise from confusing
=,==, andis, so assignments, value comparisons, and identity checks should be chosen deliberately. - Careful use of equality, identity, and membership operators leads to clearer, more predictable control flow in real-world Python programs.
