Which of the following defines a *set* in Python?
A
s = [1, 2, 3] B
s = (1, 2, 3) C
s = {1, 2, 3} D
s = <1, 2, 3>
Analysis & Theory
Sets are defined using curly braces: `{1, 2, 3}`.
What is a key characteristic of a Python set?
A
Ordered and mutable B
Unordered and allows duplicates C
Ordered and immutable D
Unordered and unique
Analysis & Theory
Sets are unordered and cannot contain duplicate values.
Which of the following values will be stored in the set?
s = {1, 2, 2, 3}
A
{1, 2, 2, 3} B
[1, 2, 2, 3] C
{1, 2, 3} D
(1, 2, 3)
Analysis & Theory
Duplicate values are removed in sets. So, `{1, 2, 3}` is stored.
What will this code output?
s = {1, 2, 3}; print(2 in s)
A
True B
False C
2 D
Error
Analysis & Theory
The `in` keyword checks if an element exists in the set — returns `True`.
What is the result of:
s = {1, 2, 3}
s.add(4)
print(s)
A
{1, 2, 3} B
{1, 2, 3, 4} C
[1, 2, 3, 4] D
(1, 2, 3, 4)
Analysis & Theory
`add()` adds a new element to the set.
How do you remove an element from a set if it might not exist?
A
remove() B
discard() C
pop() D
clear()
Analysis & Theory
`discard()` removes an element without raising an error if it doesn't exist.
What will this code output?
s = {1, 2, 3}
s.remove(4)
A
Removes 4 B
Does nothing C
Raises a KeyError D
Returns 4
Analysis & Theory
`remove()` raises a `KeyError` if the item is not found in the set.
Which method removes and returns an arbitrary element from a set?
A
remove() B
discard() C
pop() D
clear()
Analysis & Theory
`pop()` removes a random element from a set and returns it.
What does the `clear()` method do on a set?
A
Deletes one element B
Removes all elements C
Returns a list of items D
Sorts the set
Analysis & Theory
`clear()` removes all items from the set, leaving it empty.
Which of the following statements about sets is true?
A
Sets maintain insertion order B
Sets allow duplicates C
Sets are mutable D
Sets are indexed
Analysis & Theory
Sets are mutable — you can add or remove items after creation.