def add(x, xs=[]):
xs.append(x)
return xs
add(1)
print(add(2))Show answer
Answer
[1, 2] Source: Python reference: Compound statements, Python programming FAQ
16 programming language interview questions on Python, each with the correct answer and a full explanation.
def add(x, xs=[]):
xs.append(x)
return xs
add(1)
print(add(2))Answer
[1, 2] Source: Python reference: Compound statements, Python programming FAQ
fs = [lambda: i for i in range(3)]
print([f() for f in fs])Answer
[2, 2, 2] Source: Python programming FAQ
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)Answer
[[1, 0, 0], [1, 0, 0], [1, 0, 0]] Source: Python programming FAQ
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)Answer
[1, 2, 3] a = [1, 2]
b = [1, 2]
print(a == b, a is b)Answer
Source: Python reference: Data model
d = {}
d["b"] = 1
d["a"] = 2
d["b"] = 3
print(list(d))Answer
['b', 'a'] Source: Python reference: Data model
a = [[1], [2]]
b = a.copy()
b[0].append(9)
b.append([3])
print(a)Answer
[[1, 9], [2]] Source: Python programming FAQ
g = (x * x for x in range(3))
print(sum(g), sum(g))Answer
Source: Python reference: Data model
t = ([1],)
try:
t[0] += [2]
except TypeError:
passAnswer
([1, 2],) Source: Python programming FAQ
print(-7 // 2, -7 % 2)Answer
Source: Python programming FAQ
Answer
Source: Python reference: Data model
def make():
count = 0
def inc():
count += 1
return count
return inc
inc = make()
inc()Answer
Source: Python programming FAQ
def f():
try:
return 1
finally:
return 2Answer
Source: Python reference: Compound statements, PEP 765: Disallow return, break and continue that exit a finally block
Answer
Answer
Answer
Source: Python programming FAQ
These questions come from the Language Gotchas pack in Bertopia.