Explanation: The | operator gives the union of two sets, which includes all elements from both sets.
Question 42
What is the output of this Python code?
x = {1, 2, 3}
x.add(4)
print(x)
a) {1, 2, 3, 4} b) {4} c) Error d) None of the above
Correct Answer: a) {1, 2, 3, 4}
Explanation: The add() method adds an element to the set.
Question 43
How can you remove an element from a set x in Python?
a) x.remove(value) b) x.delete(value) c) x.pop(value) d) x.discard(value)
Correct Answer: a) x.remove(value)
Explanation: The remove() method removes a specified element from the set. If the element is not found, it raises a KeyError.
Question 44
What will this Python code output?
x = {1, 2, 3}
x.remove(2)
print(x)
a) {1, 2, 3} b) {1, 3} c) Error d) None of the above
Correct Answer: b) {1, 3}
Explanation: The remove() method removes the element 2 from the set.
Question 45
How can you check if an element exists in a set x?
a) x.has(element) b) element in x c) x.exists(element) d) x.find(element)
Correct Answer: b) element in x
Explanation: The in keyword checks if an element exists in the set.
Question 46
What will this Python code output?
x = {1, 2, 3}
print(4 in x)
a) True b) False c) Error d) None
Correct Answer: b) False
Explanation: The in operator checks if 4 exists in the set x, which it does not.
Question 47
What is the output of this Python code?
x = {“a”: 1, “b”: 2, “c”: 3}
print(len(x))
a) 3 b) 2 c) 1 d) Error
Correct Answer: a) 3
Explanation: The len() function returns the number of key-value pairs in the dictionary.
Question 48
What is the correct syntax to access the value associated with the key b in the dictionary x?
a) x.get(“b”) b) x[“b”] c) Both a and b d) None of the above
Correct Answer: c) Both a and b
Explanation: Both x.get("b") and x["b"] can be used to access the value of the key "b".
Question 49
What will this Python code output?
x = {“a”: 1, “b”: 2}
y = x.get(“c”, 5)
print(y)
a) 1 b) 2 c) 5 d) Error
Correct Answer: c) 5
Explanation: The get() method returns the value for the key "c" if found; otherwise, it returns the default value 5.
Question 50
What will this Python code output?
x = {“a”: 1, “b”: 2}
x.update({“b”: 3, “c”: 4})
print(x)
a) {“a”: 1, “b”: 3, “c”: 4} b) {“a”: 1, “b”: 2} c) {“b”: 3, “c”: 4} d) Error
Correct Answer: a) {"a": 1, "b": 3, "c": 4}
Explanation: The update() method updates the dictionary with the specified key-value pairs. In this case, the value of key "b" is updated, and key "c" is added.