Quiz · Medium
Read short Python snippets and predict the output. Covers aliasing, integer division, slicing, mutable defaults, scope, identity vs equality and other classic gotchas.
What does this code print?
x = [1, 2, 3]
y = x
y.append(4)
print(x)[1, 2, 3]
[1, 2, 3, 4]
None
An error
y = x does not copy the list; both names point to the same object. Appending through y changes the list that x also refers to. Use x.copy() or x[:] for an independent copy.
What does this code print?
print(7 // 2, 7 % 2, 7 / 2)3.5 1 3.5
3 1 3
3 1 3.5
4 1 3.5
// is floor division (3), % is the remainder (1), and / is true division, which always returns a float in Python 3 (3.5).
What does this code print?
print(-7 // 2)-4
-3
-3.5
3
Floor division rounds toward negative infinity, not toward zero. −3.5 floors to −4. Many people expect −3 because C and Java truncate toward zero.
What does this code print?
s = "studyfox"
print(s[2:5], s[-3:])tud fox
udy fox
udyf fox
udy ox
Indexes start at 0: s(0) t(1) u(2) d(3) y(4). The slice [2:5] includes 2 but stops before 5, giving udy. [-3:] takes the last three characters, fox.
What does this code print?
def add(item, bucket=[]):
bucket.append(item)
return bucket
add(1)
print(add(2))[1, 2]
[2]
[1]
An error
Default values are evaluated once, when the function is defined, so every call shares the same list. The fix is bucket=None and creating a new list inside the function.
What does this code print?
print([n * n for n in range(5) if n % 2 == 0])[0, 4, 16]
[4, 16]
[0, 1, 4, 9, 16]
[1, 9]
range(5) is 0–4. The filter keeps the even numbers 0, 2 and 4, whose squares are 0, 4 and 16. Forgetting that 0 is even gives [4, 16].
What does this code print?
d = {"a": 1, "b": 2}
d["a"] += 10
print(d.get("c", 0) + d["a"])KeyError
11
12
1
d["a"] becomes 11. get returns the default 0 for the missing key instead of raising KeyError (only d["c"] would raise). 0 + 11 = 11.
What does this code print?
print(0.1 + 0.2 == 0.3)True
0.3
False
An error
0.1 and 0.2 cannot be stored exactly in binary floating point; their sum is 0.30000000000000004. Compare floats with math.isclose() instead of ==.
What does this code print?
x = 5
def f():
x = 10
return x
f()
print(x)5
10
None
An error
Assigning x = 10 inside the function creates a new local variable that disappears when the function returns. The global x is untouched. You would need global x to change it.
What does this code print?
a = [1, 2]
b = [1, 2]
print(a == b, a is b)True True
True False
False False
False True
== compares values (same contents, so True). is compares identity, and these are two separate list objects, so False. Use is mainly for None checks.
What does this code print?
a, b = 1, 2
a, b = b, a + b
print(a, b)2 4
1 3
2 3
2 2
The right side is evaluated completely first, giving (2, 1 + 2) = (2, 3), and then assigned. That is why this swap-style update works without a temporary variable. Updating one at a time would give 2 4.
What does this code print?
words = ["kiwi", "fig", "banana", "apple"]
print(sorted(words, key=len))['apple', 'banana', 'fig', 'kiwi']
['fig', 'kiwi', 'apple', 'banana']
['banana', 'apple', 'kiwi', 'fig']
[3, 4, 5, 6]
key=len sorts by length: fig (3), kiwi (4), apple (5), banana (6). It returns the words, not the lengths. Alphabetical order is what you get without a key.
What does this code print?
grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)[[1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0]]
[[1, 1, 1], [0, 0, 0]]
An error
* 2 copies the reference to the same inner list, so both rows are one object. Build grids with [[0] * 3 for _ in range(2)] to get independent rows.
What does this code print?
def f():
try:
return "try"
finally:
print("finally", end=" ")
print(f())try finally
try
finally
finally try
The finally block always runs before the function actually returns, so it prints first. Then the outer print shows the returned value.
What does this code print?
s = "hello"
s.upper()
print(s)hello
HELLO
None
Hello
Strings are immutable. upper() returns a new string, which is thrown away here. You need s = s.upper() to keep it.
What does this code print?
print(list(zip([1, 2, 3], "ab")))[(1, 'a'), (2, 'b'), (3, None)]
[(1, 'a'), (2, 'b'), (3, '')]
[(1, 'a'), (2, 'b')]
An error
zip stops at the shortest input, so the 3 is dropped. Use itertools.zip_longest if you want to pad the shorter one.