Quiz · Hard
Predict the output of tricky Python snippets: closures, mutable defaults, aliasing, scope, generators and slicing.
What does this print?
fs = [lambda: i for i in range(3)]
print([f() for f in fs])[0, 1, 2]
[3, 3, 3]
[2, 2, 2]
Error
The lambdas capture the variable i, not its value at creation. After the loop i is 2, so all return 2. Use lambda i=i: i to capture values.
What does this print?
def add(x, bucket=[]):
bucket.append(x)
return bucket
print(add(1))
print(add(2))[1] then [1, 2]
[1] then [2]
[1, 2] then [1, 2]
Error
The default list is created once when the function is defined and is shared between calls.
What does this print?
grid = [[0] * 2] * 2
grid[0][0] = 1
print(grid)[[1, 0], [0, 0]]
[[1, 1], [0, 0]]
[[0, 0], [0, 0]]
[[1, 0], [1, 0]]
The outer multiplication repeats a reference to the same inner list, so both rows change.
What does this print?
def f():
try:
return 'a'
finally:
print('b')
print(f())a
b then a
a then b
b
The finally block prints 'b' while the function is returning; then print shows 'a'.
What is sum(x for x in range(5) if x % 2)?
10
6
4
0
The odd numbers below 5 are 1 and 3: 1 + 3 = 4. The truthy test x % 2 is 1 for odd numbers.
What does this print?
x = 10
def f():
print(x)
x = 5
f()UnboundLocalError
10
5
None
Because x is assigned inside f, Python treats it as local for the whole function; reading it before assignment raises UnboundLocalError.
What is 'abcdef'[1:5:2]?
'bcde'
'ace'
'bdf'
'bd'
Start at index 1, stop before 5, step 2: indices 1 and 3, so 'b' and 'd'.
What is the output?
print(len({1, 2, 2, 3}), len([1, 2, 2, 3]))4 4
3 4
3 3
4 3
The set removes the duplicate 2 (3 elements); the list keeps it (4 elements).
What does list(zip('ab', [1, 2, 3])) return?
[('a', 1), ('b', 2), (None, 3)]
[('a', 1), ('b', 2), ('', 3)]
[('a', 1), ('b', 2)]
Error: lengths differ
zip stops at the shortest iterable.
What is (lambda x, y=2: x ** y)(3)?
9
6
8
Error
y defaults to 2, so 3 ** 2 = 9.
Which expression correctly tests that n is a positive power of two?
n % 2 == 0
n & 1 == 0
n >> 1 == n
n > 0 and n & (n - 1) == 0
A power of two has a single 1 bit, so clearing the lowest set bit with n & (n − 1) gives 0. n % 2 == 0 is true for 6 too.
What does '3' + '4' give in Python, and what does int('3') + int('4') give?
7 and 7
'34' and 7
'7' and 7
Error and 7
+ concatenates strings and adds integers.
Which statement about is and == is correct?
is compares values
== compares identity
is checks whether two names refer to the same object
They are always interchangeable
== compares values (it calls __eq__). is compares object identity; use it for None.
What does this print?
def gen():
yield 1
yield 2
g = gen()
print(next(g), next(g))1 2
1 1
[1, 2]
StopIteration
Each next() resumes the generator to its next yield.
What is the result of divmod(-7, 2)?
(-3, -1)
(-3, 1)
(-4, -1)
(-4, 1)
Floor division gives −4 and the remainder has the sign of the divisor: −7 = (−4) × 2 + 1.
A function takes def f(*args, **kwargs) and is called f(1, 2, a=3). What are args and kwargs?
[1, 2] and ['a']
(1, 2) and {'a': 3}
(1, 2, 3) and {}
{1, 2} and {'a': 3}
args is a tuple of positional arguments and kwargs a dict of keyword arguments.
A recursive function lacks a base case. What happens in Python?
It returns None
It runs forever without error
RecursionError after about 1,000 nested calls
SyntaxError
Each call adds a frame to the call stack until the recursion limit is exceeded.