Exercise: Tricky Questions
Questions for: Tricky Questions
What is the output of the following Python code?
a = [1, 2, 3]
b = a[:]
a[0] = 10
print(b)
A:
[1, 2, 3]
B:
[10, 2, 3]
C:
This code will result in an error.
D:
[10, 2, 3] (but with a warning)
Answer: A
Slicing creates a new copy of the list, so modifying
a does not affect b.
Consider the following Python code:
class CustomClass:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
obj1 = CustomClass(10)
obj2 = CustomClass(10)
result = obj1 == obj2
print(result)
What will be the value of result?
A:
True
B:
False
C:
This code will result in an error.
D:
This code will result in an infinite loop.
Answer: A
The custom
__eq__ method is defined to compare the value attribute of the objects.Discuss About this Question.
What is the output of the following Python code?
result = 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1
print(result)
A:
0.5000000000000001
B:
0.6
C:
0.4
D:
0.0
Answer: A
Floating-point arithmetic may result in small precision errors, and the actual result is approximately 0.5.
Discuss About this Question.
What will be the output of the following Python code?
def outer_func(x):
def inner_func():
return x + 1
return inner_func
closure1 = outer_func(5)
closure2 = outer_func(10)
print(closure1() + closure2())
A:
11
B:
16
C:
17
D:
6
Answer: C
Each closure captures the value of
x from its own outer function call, resulting in 6 + 11 = 17.Discuss About this Question.
What is the output of the following Python code?
x = [1, 2, 3]
y = x + [4, 5]
z = x.extend([4, 5])
print(x, y, z)
A:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] None
B:
[1, 2, 3] [1, 2, 3, 4, 5] None
C:
[1, 2, 3, 4, 5] [1, 2, 3] None
D:
[1, 2, 3] [1, 2, 3] None
Answer: A
x is a list with values [1, 2, 3].
y is the result of concatenating x with [4, 5].
z is the result of extending x with [4, 5], but it returns None.
The values of x, y, and z are printed.
Thus, the output is [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] None.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.