All sample questions / Python
What does print(sorted(b - a)) print? Python Dictionaries, Sets and Comprehensions
Block 5, Dictionaries, Sets and Comprehensions, question 16 of the Python sample
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(b - a))
What does this print?
Show the answer and why each option is right or wrong
Answer, B. [4]
- A. [2, 3, 4]
- Assumes the minus operator removes nothing here since the sets overlap heavily. b - a still actively removes any element of b that is also present in a, 2 and 3 are shared and get removed, only 4, which is unique to b, remains.
- B. [4]
- Correct. b - a keeps only the elements of b that are not present in a, 2 and 3 are shared with a and get removed, leaving 4 as the only element unique to b.
- C. [1, 2, 3]
- Assumes the difference of two sets keeps everything except the truly identical set, essentially returning b unchanged. Set difference removes exactly the elements common to both sets, since a and b share 2 and 3, those two elements are dropped from the result.
- D. [1]
- Confuses this difference with a - b computed on the same two sets, which would remove different elements. b - a keeps elements of b missing from a, that is 4 alone, computing it the other way around is what would give 1 as the only leftover element.
Set difference is order sensitive, b - a and a - b answer different questions, one asks what is in b but not a, the other asks what is in a but not b. Here only the number 4 belongs to b and not to a, so it is the sole survivor.
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.