All sample questions / Python

What does print(sorted(a | b)) print? Python Dictionaries, Sets and Comprehensions

Block 5, Dictionaries, Sets and Comprehensions, question 6 of the Python sample

a = {1, 2, 3}
b = {3, 4, 5}
print(sorted(a | b))

What does this print?

  1. A. [1, 2, 3, 3, 4, 5]
  2. B. [3]
  3. C. [1, 2, 3, 4, 5]
  4. D. [1, 2]
Show the answer and why each option is right or wrong

Answer, C. [1, 2, 3, 4, 5]

A. [1, 2, 3, 3, 4, 5]
Assumes the shared element 3 appears twice in the union because it exists in both sets. A set can never hold a duplicate value, an element that belongs to both operands still appears only once in the union.
B. [3]
Assumes | computes the intersection of the two sets instead of their union. The | operator is set union, it combines every element from both sets, the shared element 3 is not the only thing kept.
C. [1, 2, 3, 4, 5]
Correct. The union operator combines every distinct element from both sets, giving all of 1 through 5 once each, since 3 is shared it still only appears a single time.
D. [1, 2]
Assumes union keeps only the elements unique to the first set, similar to a difference operation. Union keeps every element present in either set, elements from b, like 4 and 5, are included too.

The | operator on two sets returns their union, a new set containing every element that appears in either operand, with duplicates naturally collapsed since a set cannot hold the same value twice. sorted() is used here only to get a deterministic printable order, it does not change which elements are present.

The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 Python questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free Python sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.