OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

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
Choose one option.
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:

  1. a = {4, 5, 6} creates a set with three elements
  2. b = {2, 8, 6} creates another set with three elements
  3. a + b attempts to apply the + operator to two sets
  4. 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