What is the output of the following Python program?
s = {3, 1, 3, 2, 1}
print(len(s), sorted(s))
A set keeps each value once, so only 1, 2 and 3 remain.
Sets · Exercise 2 of 4
Read each Python program and choose what it prints. Every program was run on Python 3, so the answers are the real output.
What is the output of the following Python program?
s = {3, 1, 3, 2, 1}
print(len(s), sorted(s))
A set keeps each value once, so only 1, 2 and 3 remain.
What is the output of the following Python program?
print(type({}).__name__, type(set()).__name__, type({1}).__name__, type({1: 2}).__name__)
Empty braces are a dict. Braces with values make a set; with key: value pairs, a dict.
What is the output of the following Python program?
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b, a & b, a - b, a ^ b)
| everything, & common, a - b only in a, ^ in exactly one set.
What is the output of the following Python program?
print({1, 2} <= {1, 2, 3}, {1, 2} < {1, 2}, {1, 2}.isdisjoint({3}), {1, 2, 3} >= {3})
A set is a subset of itself but not a proper subset. {1, 2} and {3} share nothing, so they are disjoint.
What is the output of the following Python program?
s = {1, 2}
s.add(2)
s.add(3)
s.discard(10)
print(s, len(s))
Adding an existing element changes nothing, and discard() ignores a missing one.
What is the output of the following Python program?
letters = set("mississippi")
print(len(letters), sorted(letters))
set() of a string collects its distinct characters; sorted() returns them as an alphabetical list.
What is the output of the following Python program?
print({1, True, 1.0, 2}, len({0, False, ""}), {True, 1})
Equal values with equal hashes are one element, and the first one added is kept: 1 in the first set, True in the last. 0 and False merge, but "" is different.
What is the output of the following Python program?
s = {1}
s.update([2, 3], (4,))
s.add((5, 6))
print(len(s), (5, 6) in s, 5 in s)
update() adds each element of each iterable (2, 3, 4); add() inserts the tuple (5, 6) as a single element.
What is the output of the following Python program?
print({x % 3 for x in range(10)}, sorted({len(w) for w in ["hi", "to", "sea", "a"]}))
Only the distinct remainders 0, 1, 2 and the distinct lengths 1, 2, 3 survive.
What is the output of the following Python program?
fs = frozenset([1, 2])
d = {fs: "pair"}
print(d[frozenset([2, 1])], fs | {3}, type(fs | {3}).__name__)
Order does not matter, so frozenset([2, 1]) finds the same key. The result of an operation takes the type of the left operand.
Timed online tests with instant scores and explanations.