Junior
What objects can be placed in a set in Python?
sobes.tech AI
Answer from AI
In Python, you can place immutable (hashable) objects into a set.
These include:
- Numbers (integers, floats, complex)
- Strings
- Tuples (provided all elements of the tuple are also immutable)
- Frozenset (immutable version of set)
Objects that cannot be placed into a set:
- Lists
- Sets (but you can use frozenset)
- Dictionaries
Example:
# Immutable objects that can be placed into a set
valid_set = {1, "apple", (1, 2), frozenset({3, 4})}
# Mutable objects that cannot be placed into a set
# invalid_set = {[1, 2], {3, 4}, {"a": 1}} # Will raise TypeError when trying to create
Hashing is the process of computing a fixed value (hash) for an object. For an object to be hashable, it must have the __hash__() method, and its hash value must not change during its lifetime. Immutable objects in Python are inherently hashable.