Python Programming - Tricky Questions
Exercise : Tricky Questions - General Questions
- Tricky Questions - General Questions
41.
What is the output of the following Python code?
a = [1, 2, 3]
b = a
a = a + [4, 5]
print(b)
Answer: Option
Explanation:
The concatenation creates a new list, and
b
still refers to the original list.
42.
What will be the output of the following Python code?
class Parent:
def __init__(self, x):
self.x = x
class Child(Parent):
def __init__(self, x, y):
super().__init__(x)
self.y = y
obj = Child(10, 20)
result = obj.x * obj.y
print(result)
Answer: Option
Explanation:
The child class
Child
initializes x
and y
, and the result is the product of these attributes.
43.
Consider the following Python code:
def my_generator():
for i in range(5):
yield i * 2
result = list(my_generator())
print(result)
What will be the output of this code?
Answer: Option
Explanation:
The generator yields values multiplied by 2 in the range [0, 2, 4, 6, 8].
44.
What is the output of the following Python code?
x = [1, 2, 3]
y = x
x += [4, 5]
print(y)
Answer: Option
Explanation:
The
+=
operator modifies the list in-place, and y
reflects this change.
45.
What will be the output of the following Python code?
class MyClass:
x = 10
obj1 = MyClass()
obj2 = MyClass()
obj1.x += 5
result = obj2.x
print(result)
Answer: Option
Explanation:
The code defines a class called
When
When
Finally,
MyClass
with a class variable x
set to 10.
obj1
and obj2
are both instances of the MyClass
class.
When
obj1.x += 5
is executed, it modifies the x
attribute of obj1
by adding 5
to its current value. Since obj1
does not have its own x
attribute, it accesses the class variable x
and performs the addition. As a result, obj1.x
becomes 15.
When
result = obj2.x
is executed, it assigns the value of obj2.x
to the variable result
. Since obj2
does not have its own x
attribute, it also accesses the class variable x
. Therefore, result is 10
.
Finally,
10
is printed to the console as the output of the code.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers