Python
The Data Model: Identity & Mutability
28 flashcards · answers and spaced-repetition review in the KnowCard app
Predict the output:
```
v1 = [1, 2, 3]
v2 = v1
v3 = [1, 2, 3]
print(v1 == v3, v1 is v3)
print(v1 == v2, v1 is v2)
```
Every non-speed: a colleague checks if x is 1000: and it returns False even though x == 1000. What's the rule that explains both this and why x is 256 sometimes 'works'?
Does assignment b = a copy the object that a refers to?
Predict the output:
```
a = "water "
b = a
a += "bottle"
print(a)
print(b)
```
Predict the output:
```
a = [1, 2]
b = a
a += [3, 4]
print(a)
print(b)
```
Why does the SAME += line leave an aliased str untouched but mutate an aliased list?
Classify each as mutable or immutable: list, dict, set, int, str, tuple, frozenset.
A tuple is immutable — so this must raise an error, right?
```
t = ([1, 2], 3)
t[0].append(99)
```
Why can a tuple containing a list not be used as a dict key, even though tuples are immutable?
What value should a function's default argument NEVER be, and what happens if it is?
```
def add(item, bag=[]):
bag.append(item)
return bag
```
What does del v1 actually delete — the object, or something else?
Predict the output:
```
a = [1, 2, 3]
b = a
del a
print(b)
```
How does Python decide an object can be garbage collected?
Predict the output:
```
number1 = 1987.0
number2 = 1987
print(number1 == number2)
print(type(number1) == type(number2))
```
Predict the output:
```
print("1234" == 1234)
```
What is the correct way to say what type tells you, given this code?
```
x = "hi"
x = 1789
```
The correct, idiomatic way to test whether a variable is None: x == None or x is None?
Why is it safe for Python to let two separate a = 1; b = 1 assignments share ONE int object, but not two lists?
What does the id() function return, and what can you rely on about it?
Predict the output:
```
def tag(name, log={}):
log[name] = True
return log
print(tag("a"))
print(tag("b"))
```
In a = b + c, which happens first: binding the name a, or evaluating b + c?
What three components does every Python instance have, and which operator or function exposes each?
How do you check an instance's type, and what do type(v) == int and type(v) == type(other) each test?
If a type doesn't define == for a particular comparison, what does Python compare instead?
What exactly is a 'side effect' in Python, and is it caused specifically by the += operator?
What does hash(obj) return, why does hash([1, 2, 3]) fail, and how does this relate to dict keys?
You print hash('hello'), restart Python, and get a different number. Bug or expected?
A method returns self.data (a list). Why can that let outside callers corrupt the object, and what's the fix?
Start learning today
Free to start — download the app or use it in your browser.
