What is the output of the following code in Python?
MathWorks technical mcq question with a worked answer. Free to practise - no sign-up.
What is the output of the following code in Python?
>>> a = {4, 5, 6}
>>> b = {2, 8, 6}
>>> a + b
Show answer & explanation
Answer: A. TypeError (unsupported operand type(s) for +: 'set' and 'set')
Python sets do not support the + operator for concatenation or union operations. The + operator is not defined for set objects, so attempting to use it raises a TypeError. To combine sets, use the | (union) operator, the .union() method, or the .update() method.
Step-by-step Derivation:
Step-by-step execution:
a = {4, 5, 6}creates a set with three elementsb = {2, 8, 6}creates another set with three elementsa + battempts to apply the+operator to two sets- Python's set type does not implement
__add__(), so this raises:TypeError: unsupported operand type(s) for +: 'set' and 'set'
Correct alternatives:
a | b→ {2, 4, 5, 6, 8} (union operator)a.union(b)→ {2, 4, 5, 6, 8} (union method)- Options B and C represent valid union results but are not achievable with
+ - Option D is mathematically incorrect even if an operation were defined