Junior — Middle
Can you explain the internal structure and operation of sets in Python?
sobes.tech AI
Answer from AI
In Python, a set (set) is implemented as a hash table that stores unique elements without a specific order.
Main features of its internal structure:
- Hash table: Each element is hashed, and its hash is used to determine its position in the array.
- Uniqueness: When adding a new element, a check is performed to see if an element with the same value already exists in the table, to avoid duplicates.
- Dynamic resizing: When the table is filled above a certain threshold, it is resized to maintain performance.
Example of using a set:
s = set()
s.add(1)
s.add(2)
s.add(1) # will not be added again, as 1 already exists
print(s) # Outputs {1, 2}
Thus, operations like adding, removing, and checking for the presence of an element are performed on average in O(1) time due to hashing.