Junior
Tell about the set data type.
sobes.tech AI
Answer from AI
The set data type in Python represents an unordered collection of unique elements.
Main properties:
- Unordered: Elements in a set do not have a fixed order.
- Uniqueness: Each value can appear in the set only once.
- Mutable: Sets can add and remove elements (except
frozenset). - Elements must be hashable: Immutable data types (numbers, strings, tuples) are supported. Mutable types (lists, dictionaries) cannot be used.
Creation:
# Creating an empty set
empty_set = set()
# Creating a set from a list
my_list = [1, 2, 3, 2, 4]
set_from_list = set(my_list) # set_from_list will be {1, 2, 3, 4}
# Creating a set using curly braces
direct_set = {5, 6, 7}
Main operations:
| Operation | Method | Description |
|---|---|---|
| Add element | add(element) |
Adds element to the set. |
| Remove element | remove(element) |
Removes element. Raises an error if not present. |
| Discard element | discard(element) |
Removes element. Does nothing if not present. |
| Union | union(), ` |
` |
| Intersection | intersection(), & |
Returns a new set with common elements. |
| Difference | difference(), - |
Returns elements in the first set not in the second. |
| Symmetric difference | symmetric_difference(), ^ |
Returns elements in only one of the sets. |
| Check presence | in |
Boolean indicating if an element is in the set. |
Usage examples:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union
union_set = set1.union(set2) # union_set = {1, 2, 3, 4, 5, 6}
# Intersection
intersection_set = set1 & set2 # intersection_set = {3, 4}
# Difference
difference_set = set1 - set2 # difference_set = {1, 2}
# Check presence
is_present = 3 in set1 # is_present = True
Application in QA:
- Finding duplicates in data lists.
- Comparing two result sets (e.g., expected vs. actual).
- Filtering unique elements from a sequence.
- Checking for the presence of an element in a large data collection (fast search).
frozenset: Immutable version of a set. Used when an unchangeable set is needed (e.g., as a dictionary key).