Junior — Middle
What types of elements can be in a set in Python?
sobes.tech AI
Answer from AI
In a set in Python, only hashable (immutable) objects can be included, since sets are implemented based on a hash table. This means that the elements of a set must be immutable and have a __hash__ method.
Examples of permissible elements:
- Numbers (int, float)
- Strings (str)
- Tuples (tuple), if all their elements are also hashable
Disallowed elements:
- Lists (list)
- Dictionaries (dict)
- Sets (set)
Example:
s = {1, 'hello', (2, 3)} # correct
# s = {1, [2, 3]} # will raise a TypeError because list is not hashable