Python Data Structures: Dictionaries and Sets 5 — Questions and Answers
Question 1: What does `set.issubset()` return when called as `{1, 2}.issubset({1, 2, 3})`?
- False
- True (Correct answer)
- {1, 2}
- TypeError
Correct answer: True
`issubset()` returns True if every element of the calling set is also in the argument set.
Question 2: What is the output of `d = {'a': [1, 2]}; e = d.copy(); e['a'].append(3); print(d['a'])`?
- [1, 2]
- [1, 2, 3] (Correct answer)
- KeyError
- TypeError
Correct answer: [1, 2, 3]
`dict.copy()` performs a shallow copy, so the list value is shared between `d` and `e`; mutating it through `e` also affects `d`.
Question 3: Which method removes ALL elements from a set without deleting the set object?
- .delete()
- .remove()
- .clear() (Correct answer)
- .discard()
Correct answer: .clear()
`set.clear()` removes all elements in place, leaving an empty set object.
Question 4: What is the output of `{x**2 for x in range(4)}`?
- [0, 1, 4, 9]
- {0, 1, 4, 9} (Correct answer)
- (0, 1, 4, 9)
- {0: 0, 1: 1, 2: 4, 3: 9}
Correct answer: {0, 1, 4, 9}
Curly braces with a single expression (no colon) and a `for` clause create a set comprehension.
Question 5: What does `{1, 2, 3}.isdisjoint({4, 5, 6})` return?
- False
- True (Correct answer)
- {}
- None
Correct answer: True
`isdisjoint()` returns True when two sets share no common elements.
Question 6: What is the output of `d = dict(a=1, b=2); print('b' in d)`?
- False
- 2
- True (Correct answer)
- TypeError
Correct answer: True
The `in` operator checks for key membership in a dictionary and returns True because 'b' is a key.
Question 7: What does `Counter({'a': 3, 'b': 1}) + Counter({'a': 1, 'b': 2})` produce from `collections`?
- Counter({'a': 4, 'b': 3}) (Correct answer)
- Counter({'a': 3, 'b': 2})
- {'a': 4, 'b': 3}
- TypeError
Correct answer: Counter({'a': 4, 'b': 3})
Adding two Counters sums the counts for each key, resulting in Counter({'a': 4, 'b': 3}).
What does `set.issubset()` return when called as `{1, 2}.issubset({1, 2, 3})`?