Junior — Middle
What is the purpose of a set collection type and what are its advantages?
sobes.tech AI
Answer from AI
A set in Python is a collection type designed to store unique elements without a specific order. The main advantages of sets:
- Uniqueness of elements: automatically excludes duplicates.
- Fast search and membership testing:
inoperations are performed in amortized O(1) time. - Support for mathematical operations: union, intersection, difference, and symmetric difference.
Example of usage:
fruits = {'apple', 'banana', 'orange'}
fruits.add('kiwi')
print('banana' in fruits) # True
# Union of sets
citrus = {'orange', 'lemon'}
all_fruits = fruits.union(citrus)
print(all_fruits)
Sets are useful when uniqueness and quick access to elements are important.