Variables and Memory · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does the variable x actually store after x = [1, 2, 3]?
2. What does this print?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
3. What does this print?
a = [1, 2, 3]
b = a
b = b + [4]
print(a)
4. Why does sys.getrefcount(obj) usually report one more than you expect?
5. Which situation can reference counting not clean up on its own?
6. What does this print?
def change(items):
    items = [0, 0, 0]

data = [1, 2, 3]
change(data)
print(data)
7. What does this print?
t = ([1, 2], 'a')
t[0].append(3)
print(t)
8. Which comparison is the idiomatic way to check whether x is None?
9. What is printed?
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b, a is b)
10. Which of these is guaranteed to be True in CPython?
11. After compiling this function, which constant appears in f.__code__.co_consts?
def f():
    return 24 * 60
12. You need to check word in vocabulary millions of times. What type should vocabulary be?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Same object or just equal?

Write a function relationship(a, b) that returns:

'same object' if a and b refer to the same object, otherwise 'equal' if their values are equal, otherwise 'different'.

Hints (2)
  1. Check identity first with is. Two names for the same object are always equal too.
  2. Order matters: if you test == first, you can never return 'same object'.
Show a solution
def relationship(a, b):
    if a is b:
        return 'same object'
    if a == b:
        return 'equal'
    return 'different'

Exercise 2: A function without side effects

add_item(items, item) is supposed to return a new list with item appended, but the current version also changes the caller's list (a side effect).

Fix it so the original list is never mutated and the returned list is a different object.

Hints (2)
  1. items.append(...) mutates the shared list. Which list operation creates a new list?
  2. Alternatively, copy first with list(items) or items.copy(), then append to the copy.
Show a solution
def add_item(items, item):
    return items + [item]

Exercise 3: Count the references

Using the course's ctypes technique, write ref_count(obj) that returns how many references point to obj, not counting the temporary reference created by calling your function.

Tip: read the count from id(obj). Then think about how many extra references exist while your function is running.

Hints (2)
  1. ctypes.c_long.from_address(id(obj)).value reads the raw count.
  2. Your function's own parameter obj is one extra reference while the function is running. Subtract it.
Show a solution
import ctypes

def ref_count(obj):
    # While this function runs, its parameter `obj` holds one extra reference.
    return ctypes.c_long.from_address(id(obj)).value - 1