Junior — Middle
What types of objects can be part of a set in Python?
sobes.tech AI
Answer from AI
In Python, a set can only contain hashable objects. This means objects must be immutable and have a hash() method.
Typical objects that can be included in a set:
- Numbers (int, float, complex)
- Strings (str)
- Tuples (tuple), if all elements of the tuple are also hashable
- Boolean values (bool)
Objects that cannot be elements of a set:
- Lists (list)
- Dictionaries (dict)
- Sets (set)
Example:
s = {1, "hello", (2, 3)} # correct
s.add([4,5]) # will raise a TypeError