Practice: Identity Operators
Q1. Same list, two names
Create a list `a`, make `b = a`, and print whether `a is b`.
Goal: Understand that assignment shares objects.
Q2. Equal but not identical
Create two separate lists with the same items and print `a == b` and then `a is b` on separate lines.
Goal: Distinguish == from is.
Q3. Check for None
Write a function `describe(x)` that returns 'missing' when x is None and 'present' otherwise. Print describe(None) and describe(0).
Goal: Use is None correctly.
Q4. Make a real copy
Make list `a = [1, 2, 3]`, create an independent copy `b` with `.copy()`, and print `a is b` and `a == b`.
Goal: Copy lists safely.
Q5. Change through an alias
Make `a = [1]` and `b = a`. Append 2 using b, then print a.
Goal: See the effect of aliasing.
Q6. Count identical pairs
Given `x = [1]`, `y = x`, `z = [1]`, print how many of the pairs (x,y), (x,z), (y,z) are identical using a sum of `is` checks.
Goal: Combine identity checks.
Q7. is not with a sentinel
Create `marker = object()` and `other = object()`. Print `marker is not other`.
Goal: Use is not.
Q8. Alias result
What does this print?
a = [1, 2]
b = a
print(a is b)Goal: Read alias code.
Q9. Two equal lists
What does this print?
a = [3, 4]
b = [3, 4]
print(a == b, a is b)Goal: Read == and is together.
Q10. Slice copy
What does this print?
a = [1, 2, 3]
b = a[:]
print(a is b)Goal: Know slicing copies.
Q11. Modify via alias
What does this print?
a = [1, 2]
b = a
b.append(3)
print(a)
print(len(b))Goal: Predict aliasing effects.
Q12. None checks
What does this print?
x = None
print(x is None)
print(x is not None)Goal: Read None checks.
Q13. Identity of ids
What does this print?
a = [1]
b = a
c = [1]
print(id(a) == id(b), id(a) == id(c))Goal: Connect id and is.
Q14. Tuple of lists
What does this print?
inner = [0]
a = (inner, inner)
print(a[0] is a[1])
a[0].append(1)
print(a)Goal: Understand shared inner objects.
Q15. Fix the None check
The code should print 'empty' when no item is found, but it also says empty for index 0. Fix it.
def first_index(items, t):
for i, v in enumerate(items):
if v == t:
return i
return None
r = first_index(['a', 'b'], 'a')
if not r:
print('empty')
else:
print('found', r)Goal: Avoid truthiness bugs with None.
Q16. Fix the copy
The programmer wants `backup` to stay unchanged. Fix the code.
data = [1, 2]
backup = data
data.append(3)
print(backup)Goal: Fix aliasing bugs.
Q17. Fix string comparison
The code should compare values with ==, not identity. Fix it.
name = input()
if name is 'Asha':
print('Hi Asha')Goal: Pick == for values.
Q18. Explain is vs ==
In one or two sentences, explain the difference between `==` and `is`.
Goal: Define identity.
Q19. Why is None?
Why is `is None` preferred over `== None`?
Goal: Know the None convention.
Q20. Cache warning
Why should you not use `is` to compare two integers?
Goal: Avoid relying on caching.