1. What does this code print?
x = [1, 2, 3]
y = x
y[0] = 10
print(x)
Output: [10, 2, 3]
Explanation: y is a reference to x, so modifying y also affects x.
2. What is the result of this code?
x = {1, 2, 2, 3}
print(len(x))
Output: 3
Explanation: Sets automatically remove duplicates.
3. What does this code print?
def f(x, y=[]):
y.append(x)
return y
print(f(1))
print(f(2, []))
print(f(3))
Output:
[1]
[2]
[1, 3]
Explanation: The default list y is shared across function calls.
4. What is the output of this code snippet?
def g(x, y=2):
return x + y
print(g(1, y=3))
print(g(1))
Output:
4
3
Explanation: The function uses the default value for y if not explicitly passed.
5. What does this code print?
x = [i for i in range(3)]
y = [i for i in x]
print(x is y)
Output: False
Explanation: y is a new list created from x, so they are not the same object.
6. What is the result of this code?
x = [1, 2, 3]
x.append(x)
print(x)
Output: [1, 2, 3, [...]]
Explanation: The list contains itself, creating a recursive structure.
7. What does this code print?
x = 'abc'
y = x[::-1]
print(y)
Output: cba
Explanation: [::-1] reverses the string.
8. What is the result of this code?
x = {1: 'a', 2: 'b'}
y = x.copy()
y[3] = 'c'
print(x)
print(y)
Output:
{1: 'a', 2: 'b'}
{1: 'a', 2: 'b', 3: 'c'}
Explanation: copy creates a shallow copy of the dictionary.
9. What does this code print?
x = (1, 2, 3)
y = x * 3
print(y)
Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Explanation: * replicates the tuple.
10. What is the result of this code?
x = 'hello'
y = x[0:2] + x[2:]
print(y)
Output: hello
Explanation: The slicing does not alter the string.
11. What does this code print?
x = 'Python'
y = x[::2]
print(y)
Output: Pto
Explanation: ::2 slices the string with a step of 2.
12. What is the result of this code?
x = [1, 2, 3]
x[1:2] = [4, 5]
print(x)
Output: [1, 4, 5, 3]
Explanation: Slicing and assignment replace part of the list.
13. What does this code print?
x = [1, 2, 3]
x[1:2] = []
print(x)
Output: [1, 3]
Explanation: Replacing the slice with an empty list removes the element.
14. What is the result of this code?
x = {1, 2, 3}
x.discard(2)
x.discard(4)
print(x)
Output: {1, 3}
Explanation: discard removes an element if present, ignoring if it's not.
15. What does this code print?
def f(x, y=[]):
y.append(x)
return y
print(f(1))
print(f(2, []))
print(f(3))
Output:
[1]
[2]
[1, 3]
Explanation: The default list y persists across function calls.
16. What is the result of this code?
x = [1, 2, 3]
x.append(x)
print(len(x))
Output: 4
Explanation: The list now contains itself, making its length 4.
17. What does this code print?
x = 'Python'
print(x[1:4])
Output: yth
Explanation: Slices the string from index 1 to 3.
18. What is the result of this code?
x = (1, 2, 3)
y = (4, 5)
print(x + y)
Output: (1, 2, 3, 4, 5)
Explanation: + concatenates tuples.
19. What does this code print?
x = 'abc'
print(x.replace('b', 'x', 1))
Output: axc
Explanation: replace substitutes b with x, replacing only the first occurrence.
20. What is the result of this code?
x = 'Python'
y = x.find('t')
print(y)
Output: -1
Explanation: find returns -1 if the substring is not found.
21. What does this code print?
x = 'Python'
print(x[-1])
Output: n
Explanation: Negative indexing returns the last character.
22. What is the output of this code snippet?
x = [1, 2, [3, 4]]
y = x.copy()
y[2][0] = 5
print(x)
Output: [1, 2, [5, 4]]
Explanation: copy creates a shallow copy; nested lists are still referenced.
23. What does this code print?
x = [1, 2, 3]
x.sort(reverse=True)
print(x)
Output: [3, 2, 1]
Explanation: sort(reverse=True) sorts the list in descending order.
24. What is the result of this code?
x = {1: 'a', 2: 'b'}
y = x.setdefault(2, 'c')
print(y)
Output: b
Explanation: setdefault returns the existing value for the key 2.
25. What does this code print?
x = [1, 2, 3]
y = x
y[1] = 10
print(x)
Output: [1, 10, 3]
Explanation: y and x reference the same list.
26. What is the result of this code?
x = 'Python'
print(x[:5])
Output: Pytho
Explanation: Slicing up to index 5 returns the first five characters.
27. What does this code print?
x = {1: 'a', 2: 'b'}
x.pop(1)
print(x)
Output: {2: 'b'}
Explanation: pop removes the specified key-value pair.
28. What is the result of this code?
x = 'Python'
y = x.upper()
print(y)
Output: PYTHON
Explanation: upper converts the string to uppercase.
29. What does this code print?
x = [1, 2, 3]
y = x[:]
y[0] = 4
print(x)
Output: [1, 2, 3]
Explanation: Slicing creates a copy of the list, so x remains unchanged.
30. What is the result of this code?
x = [1, 2, 3]
print(x * 2)
Output: [1, 2, 3, 1, 2, 3]
Explanation: * repeats the list.
31. What does this code print?
x = 'hello'
print(x.capitalize())
Output: Hello
Explanation: capitalize returns the string with the first letter capitalized.
32. What is the result of this code?
x = 'Python'
y = x[::-1]
print(y)
Output: nohtyP
Explanation: [::-1] reverses the string.
33. What does this code print?
x = [1, 2, 3]
y = x.pop(1)
print(y)
Output: 2
Explanation: pop(1) removes and returns the element at index 1.
34. What is the result of this code?
x = {1, 2, 3}
y = x.union({3, 4, 5})
print(y)
Output: {1, 2, 3, 4, 5}
Explanation: union combines two sets.
35. What does this code print?
x = [1, 2, 3]
print(x[1:3])
Output: [2, 3]
Explanation: Slices the list from index 1 to 2.
36. What is the result of this code?
x = '123'
y = int(x) + 1
print(y)
Output: 124
Explanation: int(x) converts the string to an integer.
37. What does this code print?
x = 'hello'
print(x.ljust(10, '*'))
Output: hello*****
Explanation: ljust pads the string on the right with '*'.
38. What is the result of this code?
x = 'hello'
print(x.split('l'))
Output: ['he', '', 'o']
Explanation: split divides the string at each l.
39. What does this code print?
x = 'Python'
print(x.find('o'))
Output: 4
Explanation: find returns the index of the first occurrence of 'o'.
40. What is the result of this code?
x = [1, 2, 3]
x.insert(1, 10)
print(x)
Output: [1, 10, 2, 3]
Explanation: insert adds 10 at index 1.
41. What does this code print?
x = 'Python'
y = x.replace('o', 'a')
print(y)
Output: Pythan
Explanation: replace substitutes o with a.
42. What is the result of this code?
x = [1, 2, 3]
y = x.copy()
y.append(4)
print(x)
print(y)
Output:
[1, 2, 3]
[1, 2, 3, 4]
Explanation: copy creates a shallow copy; changes to y don't affect x.
43. What does this code print?
x = [1, 2, 3]
print(x.pop())
Output: 3
Explanation: pop removes and returns the last element.
44. What is the result of this code?
x = 'Python'
print(x[1:4])
Output: yth
Explanation: Slices the string from index 1 to 3.
45. What does this code print?
x = {1, 2, 3}
print(x - {2, 3})
Output: {1}
Explanation: - computes the difference between sets.
46. What is the result of this code?
x = 'hello'
print(x[1:])
Output: ello
Explanation: Slices the string from index 1 to the end.
47. What does this code print?
x = [1, 2, 3]
y = x
y[1] = 10
print(x)
Output: [1, 10, 3]
Explanation: y is a reference to x.
48. What is the result of this code?
x = [1, 2, 3]
print(len(x))
Output: 3
Explanation: len returns the number of elements in the list.
49. What does this code print?
x = 'Python'
y = x[1:5]
print(y)
Output: ytho
Explanation: Slices the string from index 1 to 4.
50. What is the result of this code?
x = [1, 2, 3]
x.extend([4, 5])
print(x)
Output: [1, 2, 3, 4, 5]
Explanation: extend adds elements from another list.
Python Class-Based Questions
1. What does this code print?
class A:
def __init__(self):
self.x = 10
class B(A):
def __init__(self):
super().__init__()
self.y = 20
obj = B()
print(obj.x, obj.y)
Output: 10 20
Explanation: super() calls the parent class's __init__ method.
2. What is the result of this code?
class A:
def __init__(self):
self.value = 1
class B(A):
def __init__(self):
super().__init__()
self.value = 2
obj = B()
print(obj.value)
Output: 2
Explanation: B's __init__ method overrides A's value.
3. What does this code print?
class A:
def __init__(self, x):
self.x = x
def __add__(self, other):
return A(self.x + other.x)
obj1 = A(10)
obj2 = A(20)
obj3 = obj1 + obj2
print(obj3.x)
Output: 30
Explanation: __add__ defines custom behavior for + operator.
4. What is the result of this code?
class A:
def __init__(self):
self.value = 1
def __repr__(self):
return f'A(value={self.value})'
obj = A()
print(obj)
Output: A(value=1)
Explanation: __repr__ defines the string representation of the object.
5. What does this code print?
class A:
def __init__(self):
self.x = 10
class B(A):
def __init__(self):
super().__init__()
self.x = 20
obj = B()
print(obj.x)
Output: 20
Explanation: B's __init__ method sets x to 20.
6. What is the result of this code?
class A:
def __init__(self):
self.value = 10
def __call__(self, x):
return self.value + x
obj = A()
print(obj(5))
Output: 15
Explanation: __call__ allows instances to be called like functions.
7. What does this code print?
class A:
def __init__(self):
self.x = 10
def method(self):
return self.x
class B(A):
def method(self):
return super().method() + 10
obj = B()
print(obj.method())
Output: 20
Explanation: super().method() calls A's method.
8. What is the result of this code?
class A:
def __init__(self):
self.x = 5
class B(A):
def __init__(self):
super().__init__()
self.x = 10
obj = B()
print(hasattr(obj, 'x'))
Output: True
Explanation: hasattr checks if obj has attribute x.
9. What does this code print?
class A:
def __init__(self):
self
.x = 10
@property
def value(self):
return self.x
obj = A()
print(obj.value)
Output: 10
Explanation: @property allows method access like an attribute.
10. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __del__(self):
print("Object deleted")
obj = A()
del obj
Output: Object deleted
Explanation: __del__ is called when an object is deleted.
11. What does this code print?
class A:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
obj1 = A(10)
obj2 = A(10)
print(obj1 == obj2)
Output: True
Explanation: __eq__ defines equality for class instances.
12. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __str__(self):
return f'A(x={self.x})'
obj = A()
print(str(obj))
Output: A(x=10)
Explanation: __str__ provides the string representation for str().
13. What does this code print?
class A:
def __init__(self):
self.x = 10
def __getitem__(self, key):
return self.x
obj = A()
print(obj[0])
Output: 10
Explanation: __getitem__ allows item access with [].
14. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
if value < 0:
raise ValueError("x cannot be negative")
super().__setattr__(key, value)
obj = A()
obj.x = 5
print(obj.x)
Output: 5
Explanation: __setattr__ customizes attribute setting.
15. What does this code print?
class A:
def __init__(self):
self.x = 10
def __iter__(self):
yield self.x
obj = A()
print(list(obj))
Output: [10]
Explanation: __iter__ makes an object iterable.
16. What is the result of this code?
class A:
x = 5
@classmethod
def set_x(cls, value):
cls.x = value
A.set_x(10)
print(A.x)
Output: 10
Explanation: @classmethod allows method access to class variables.
17. What does this code print?
class A:
def __init__(self):
self.x = 10
def __eq__(self, other):
return isinstance(other, A) and self.x == other.x
obj1 = A()
obj2 = A()
print(obj1 == obj2)
Output: True
Explanation: __eq__ checks for equality and type.
18. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
value = value * 2
super().__setattr__(key, value)
obj = A()
obj.x = 5
print(obj.x)
Output: 10
Explanation: __setattr__ modifies the value before setting.
19. What does this code print?
class A:
def __init__(self):
self.x = 10
def __del__(self):
print("Deleting object")
def __repr__(self):
return f"A(x={self.x})"
obj = A()
del obj
Output: Deleting object
Explanation: __del__ is called when the object is deleted.
20. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __call__(self, y):
return self.x + y
obj = A()
print(obj(5))
Output: 15
Explanation: __call__ makes the object callable like a function.
21. What does this code print?
class A:
def __init__(self):
self.x = 10
def __getitem__(self, index):
return self.x[index]
obj = A()
print(obj[0])
Output: 1
Explanation: __getitem__ allows index access.
22. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
Output: True
Explanation: __contains__ defines behavior for the in operator.
23. What does this code print?
class A:
def __init__(self):
self.x = 10
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
with A() as obj:
print(obj.x)
Output: 10
Explanation: __enter__ and __exit__ allow the object to be used in a with statement.
24. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __iter__(self):
return iter([self.x])
obj = A()
print(next(iter(obj)))
Output: 10
Explanation: __iter__ returns an iterator over [self.x].
25. What does this code print?
class A:
def __init__(self):
self.x = 10
@property
def value(self):
return self.x
@value.setter
def value(self, new_value):
self.x = new_value
obj = A()
obj.value = 20
print(obj.value)
Output: 20
Explanation: @property allows getter and setter methods.
26. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __str__(self):
return f'A(x={self.x})'
obj = A()
print(obj)
Output: A(x=10)
Explanation: __str__ defines the string representation for str().
27. What does this code print?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
value = value + 5
super().__setattr__(key, value)
obj = A()
obj.x = 5
print(obj.x)
Output: 10
Explanation: __setattr__ modifies the value before setting it.
28. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __eq__(self, other):
return isinstance(other, A) and self.x == other.x
obj1 = A()
obj2 = A()
print(obj1 == obj2)
Output: True
Explanation: __eq__ checks for equality of x in both instances.
29. What does this code print?
class A:
def __init__(self):
self.x = 10
def __getitem__(self, index):
return self.x
obj = A()
print(obj[0])
Output: 10
Explanation: __getitem__ defines behavior for index access.
30. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __iter__(self):
return iter([self.x])
obj = A()
print(list(iter(obj)))
Output: [10]
Explanation: __iter__ returns an iterator over [self.x].
31. What does this code print?
class A:
def __init__(self):
self.x = 10
@property
def value(self):
return self.x
@value.setter
def value(self, new_value):
self.x = new_value
obj = A()
obj.value = 20
print(obj.value)
Output: 20
Explanation: @property allows attribute-like access to getter and setter methods.
32. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __eq__(self, other):
return isinstance(other, A) and self.x == other.x
obj1 = A()
obj2 = A()
print(obj1 == obj2)
Output: True
Explanation: __eq__ defines equality comparison.
33. What does this code print?
class A:
def __init__(self):
self.x = 10
def __del__(self):
print("Object deleted")
obj = A()
Output: Object deleted
Explanation: __del__ is called when the object is deleted.
34. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __repr__(self):
return f'A(x={self.x})'
obj = A()
print(repr(obj))
Output: A(x=10)
Explanation: __repr__ defines the string representation for repr().
35. What does this code print?
class A:
def __init__(self):
self.x = 10
def __str__(self):
return f'A(x={self.x})'
obj = A()
print(obj)
Output: A(x=10)
Explanation: __str__ provides a user-friendly string representation.
36. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __iter__(self):
return iter([self.x])
obj = A()
print(next(iter(obj)))
Output: 10
Explanation: __iter__ returns an iterator over [self.x].
37. What does this code print?
class A:
def __init__(self):
self.x = 10
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
with A() as obj:
print(obj.x)
Output: 10
Explanation: __enter__ and __exit__ allow the object to be used in a with statement.
38. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
Output: True
Explanation: __contains__ defines behavior for the in operator.
39. What does this code print?
class A:
def __init__(self):
self.x = 10
def __getitem__(self, index):
return self.x
obj = A()
print(obj[0])
Output: 10
Explanation: __getitem__ allows index access.
40. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
value = value * 2
super().__setattr__(key, value)
obj = A()
obj.x = 5
print(obj.x)
Output: 10
Explanation: __setattr__ modifies the value before setting.
Here are more advanced Python syntax and output questions:
41. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
if value % 2 != 0:
raise ValueError("x must be even")
super().__setattr__(key, value)
obj = A()
obj.x = 4
print(obj.x)
Output: 4
Explanation: __setattr__ ensures that x can only be set to an even value.
42. What does this code print?
class A:
def __init__(self):
self.x = 10
def __call__(self, y):
return self.x + y
obj = A()
print(obj(3) + obj(4))
Output: 17
Explanation: __call__ allows an object to be called as a function.
43. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __add__(self, other):
if isinstance(other, A):
return self.x + other.x
return NotImplemented
obj1 = A()
obj2 = A()
print(obj1 + obj2)
Output: 20
Explanation: __add__ defines behavior for the + operator with another A instance.
44. What does this code print?
class A:
def __init__(self):
self.x = [1, 2, 3]
def __len__(self):
return len(self.x)
obj = A()
print(len(obj))
Output: 3
Explanation: __len__ provides the length of the object.
45. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
print(5 in obj)
Output:
True
False
Explanation: __contains__ checks membership using in.
46. What does this code print?
class A:
def __init__(self):
self.x = 10
def __eq__(self, other):
if not isinstance(other, A):
return False
return self.x == other.x
obj1 = A()
obj2 = A()
print(obj1 == obj2)
print(obj1 == 10)
Output:
True
False
Explanation: __eq__ checks for equality with type checking.
47. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __iadd__(self, other):
if isinstance(other, int):
self.x += other
return self
obj = A()
obj += 5
print(obj.x)
Output: 15
Explanation: __iadd__ defines behavior for in-place addition (+=).
48. What does this code print?
class A:
def __init__(self):
self.x = 10
def __getitem__(self, key):
return self.x + key
obj = A()
print(obj[5])
Output: 15
Explanation: __getitem__ defines behavior for item access with [].
49. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __setitem__(self, key, value):
if key == 0:
self.x = value
obj = A()
obj[0] = 20
print(obj.x)
Output: 20
Explanation: __setitem__ allows setting items using [].
50. What does this code print?
class A:
def __init__(self):
self.x = 10
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.x = 0
with A() as obj:
print(obj.x)
Output: 10
Explanation: __enter__ sets up the context, and __exit__ can modify the object when
the context ends.
51. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __str__(self):
return f'A({self.x})'
def __repr__(self):
return f'A(x={self.x})'
obj = A()
print(str(obj))
print(repr(obj))
Output:
A(10)
A(x=10)
Explanation: __str__ is for user-friendly output, while __repr__ is for debugging.
52. What does this code print?
class A:
def __init__(self):
self.x = 10
def __getattr__(self, name):
return f'{name} not found'
obj = A()
print(obj.y)
Output: y not found
Explanation: __getattr__ is called when an attribute is accessed that does not exist.
53. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
value = value + 1
super().__setattr__(key, value)
obj = A()
obj.x = 5
print(obj.x)
Output: 6
Explanation: __setattr__ modifies the value before setting it.
54. What does this code print?
class A:
def __init__(self):
self.x = 10
def __call__(self, *args, **kwargs):
return sum(args)
obj = A()
print(obj(1, 2, 3))
Output: 6
Explanation: __call__ makes the object callable with *args.
55. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __del__(self):
print("Object deleted")
obj = A()
obj = None
Output: Object deleted
Explanation: __del__ is called when an object is garbage collected.
56. What does this code print?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
print(20 in obj)
Output:
True
False
Explanation: __contains__ allows using in to check membership.
57. What is the result of this code?
class A:
def __init__(self):
self.x = [1, 2, 3]
def __getitem__(self, index):
return self.x[index]
obj = A()
print(obj[1])
Output: 2
Explanation: __getitem__ allows indexing into the object.
58. What does this code print?
class A:
def __init__(self):
self.x = 10
def __setattr__(self, key, value):
if key == 'x':
value = value ** 2
super().__setattr__(key, value)
obj = A()
obj.x = 5
print(obj.x)
Output: 25
Explanation: __setattr__ modifies the value before setting it.
59. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __eq__(self, other):
if not isinstance(other, A):
return NotImplemented
return self.x == other.x
obj1 = A()
obj2 = 10
print(obj1 == obj2)
Output: False
Explanation: __eq__ returns NotImplemented for incompatible types.
60. What does this code print?
class A:
def __init__(self):
self.x = 10
def __repr__(self):
return f'A({self.x})'
obj = A()
print(obj)
Output: A(10)
Explanation: __repr__ is used for the official string representation.
61. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __len__(self):
return len(str(self.x))
obj = A()
print(len(obj))
Output: 2
Explanation: __len__ uses the length of the string representation of x.
62. What does this code print?
class A:
def __init__(self):
self.x = 10
def __str__(self):
return f'Value is {self.x}'
obj = A()
print(str(obj))
Output: Value is 10
Explanation: __str__ defines a user-friendly string representation.
63. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __getattr__(self, name):
return f'{name} not found'
def __getattribute__(self, name):
if name == 'x':
return 20
return super().__getattribute__(name)
obj = A()
print(obj.x)
print(obj.y)
Output:
20
y not found
Explanation: __getattribute__ intercepts attribute access before __getattr__.
64. What does this code print?
class A:
def __init__(self):
self.x = 10
def __iter__(self):
yield self.x
obj = A()
print(list(iter(obj)))
Output: [10]
Explanation: __iter__ defines the iterator protocol.
65. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
print(20 in obj)
Output:
True
False
Explanation: __contains__ checks for membership.
66. What does this code print?
class A:
def __init__(self):
self.x = 10
def __call__(self, *args):
return len(args)
obj = A()
print(obj(1, 2, 3))
print(obj())
Output:
3
0
Explanation: __call__ allows the object to be used as a function.
67. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __getitem__(self, index):
return self.x + index
obj = A()
print(obj[0])
print(obj[1])
Output:
10
11
Explanation: __getitem__ supports item access with indices.
68. What does this code print?
class A:
def __init__(self):
self.x = 10
def __setitem__(self, index, value):
if index == 0:
self.x = value
obj = A()
obj[0] = 20
print(obj.x)
Output: 20
Explanation: __setitem__ allows setting items using indices.
69. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __delitem__(self, index):
if index == 0:
del self.x
obj = A()
del obj[0]
print(hasattr(obj, 'x'))
Output: False
Explanation: __delitem__ allows deletion of items using indices.
70. What does this code print?
class A:
def __init__(self):
self.x = 10
def __eq__(self, other):
if isinstance(other, A):
return self.x == other.x
return False
def __ne__(self, other):
return not self.__eq__(other)
obj1 = A()
obj2 = A()
print(obj1 != obj2)
Output: False
Explanation: __ne__ is used for the inequality operator.
71. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __lt__(self, other):
return self.x < other.x
obj1 = A()
obj2 = A()
print(obj1 < obj2)
Output: False
Explanation: __lt__ defines behavior for the less-than operator.
72. What does this code print?
class A:
def __init__(self):
self.x = 10
def __radd__(self, other):
return self.x + other
obj = A()
print(5 + obj)
Output: 15
Explanation: __radd__ defines behavior for reverse addition with +.
73. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __mul__(self, other):
return self.x * other
obj = A()
print(obj * 5)
Output: 50
Explanation: __mul__ defines behavior for the multiplication operator.
74. What does this code print?
class A:
def __init__(self):
self.x = 10
def __mod__(self, other):
return self.x % other
obj = A()
print(obj % 3)
Output: 1
Explanation: __mod__ defines behavior for the modulo operator.
75. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __floordiv__(self, other):
return self.x // other
obj = A()
print(obj // 3)
Output: 3
Explanation: __floordiv__ defines behavior for integer division (//).
76. What does this code print?
class A:
def __init__(self):
self.x = 10
def __and__(self, other):
return self.x & other
obj = A()
print(obj & 3)
Output: 2
Explanation: __and__ defines behavior for the bitwise & operator.
77. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __or__(self, other):
return self.x | other
obj = A()
print(obj | 3)
Output: 11
Explanation: __or__ defines behavior for the bitwise | operator.
78. What does this code print?
class A:
def __init__(self):
self.x = 10
def __xor__(self, other):
return self.x ^ other
obj = A()
print(obj ^ 3)
Output: 9
Explanation: __xor__ defines behavior for the bitwise ^ operator.
79. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __lshift__(self, other):
return self.x << other
obj = A()
print(obj << 2)
Output: 40
Explanation: __lshift__ defines behavior for the left shift operator.
80. What does this code print?
class A:
def __init__(self):
self.x = 10
def __rshift__(self, other):
return self.x >> other
obj = A()
print(obj >> 2)
Output: 2
Explanation: __rshift__ defines behavior for the right shift operator.
81. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __neg__(self):
return -self.x
obj = A()
print(-obj)
Output: -10
Explanation: __neg__ defines behavior for the unary negation operator (-).
82. What does this code print?
class A:
def __init__(self):
self.x = 10
def __pos__(self):
return +self.x
obj = A()
print(+obj)
Output: 10
Explanation: __pos__ defines behavior for the unary positive operator (+).
83. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
print(20 in obj)
Output:
True
False
Explanation: __contains__ checks if the item is in the object.
84. What does this code print?
class A:
def __init__(self):
self.x = 10
def __repr__(self):
return f'Value: {self.x}'
def __str__(self):
return f'{self.x}'
obj = A()
print(repr(obj))
print(str(obj))
Output:
Value: 10
10
Explanation: __repr__ and __str__ provide different string representations.
85. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __add__(self, other):
return self.x + other
obj = A()
print(obj + 5)
Output: 15
Explanation: __add__ defines behavior for addition with another value.
86. What does this code print?
class A:
def __init__(self):
self.x = 10
def __sub__(self, other):
return self.x - other
obj = A()
print(obj - 5)
Output: 5
Explanation: __sub__ defines behavior for subtraction.
87. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __divmod__(self, other):
return divmod(self.x, other)
obj = A()
print(divmod(obj, 3))
Output: (3, 1)
Explanation: __divmod__ defines behavior for the divmod function.
88. What does this code print?
class A:
def __init__(self):
self.x = 10
def __reversed__(self):
return reversed([self.x])
obj = A()
print(list(reversed(obj)))
Output: [10]
Explanation: __reversed__ defines behavior for the reversed() function.
89. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
with A() as obj:
print(obj.x)
Output: 10
Explanation: __enter__ and __exit__ define context management behavior.
90. What does this code print?
class A:
def __init__(self):
self.x = 10
def __hash__(self):
return hash(self.x)
obj = A()
print(hash(obj))
Output: The hash value of 10 (depends on the Python implementation)
Explanation: __hash__ defines the hash value of the object.
91. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __iter__(self):
return iter([self.x])
obj = A()
print(list(obj))
Output: [10]
Explanation: __iter__ defines behavior for iterating over the object.
92. What does this code print?
class A:
def __init__(self):
self.x = 10
def __call__(self, *args, **kwargs):
return len(args) + len(kwargs)
obj = A()
print(obj(1, 2, 3, a=4, b=5))
Output: 5
Explanation: __call__ can use arguments to compute a result.
93. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __get__(self, instance, owner):
return self.x
obj = A()
print(obj.__get__(None, None))
Output: 10
Explanation: __get__ is part of the descriptor protocol.
94. What does this code print?
class A:
def __init__(self):
self.x = 10
def __set__(self, instance, value):
self.x = value
obj = A()
obj.__set__(None, 20)
print(obj.x)
Output: 20
Explanation: __set__ is part of the descriptor protocol.
95. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __del__(self):
print("Deleted")
obj = A()
del obj
Output: Deleted
Explanation: __del__ is called when the object is deleted.
96. What does this code print?
class A:
def __init__(self):
self.x = 10
def __str__(self):
return f'A with x={self.x}'
obj = A()
print(f'The object is: {obj}')
Output: The object is: A with x=10
Explanation: __str__ provides the string representation used in formatted strings.
97. What is the result of this code?
class A:
def __init__(self):
self.x = 10
def __repr__(self):
return f'A({self.x})'
obj = A()
print(f'{obj!r}')
Output: A(10)
Explanation: !r uses __repr__ for the formatted string.
98. What does this code print?
class A:
def __init__(self):
self.x = 10
def __contains__(self, item):
return self.x == item
obj = A()
print(10 in obj)
print(20 in obj)