Junior
What is a set in Python?
sobes.tech AI
Answer from AI
A set is a mutable, unordered collection of unique elements. Elements must be hashable.
Main characteristics:
- Unordered: Elements are not stored in a specific order.
- Unique: Duplicates are automatically removed.
- Mutable: Elements can be added and removed.
- Hashable: Elements must be immutable types (numbers, strings, tuples).
Examples of creation:
# Creating from a list
my_set = set([1, 2, 3, 1, 4]) # {1, 2, 3, 4}
# Creating using curly braces
another_set = {5, 6, 7, 7} # {5, 6, 7}
# Empty set
empty_set = set() # {}
Main operations:
| Operation | Description | Example | Result |
|---|---|---|---|
add() |
Add an element | s.add(10) |
{1, 2, 3, 4, 10} |
remove() |
Remove an element (with error) | s.remove(2) |
{1, 3, 4} |
discard() |
Remove an element (without error) | s.discard(5) |
{1, 2, 3, 4} |
clear() |
Clear the set | s.clear() |
{} |
| `union( | )` | Union | `s1 |
intersection(&) |
Intersection | s1 & s2 |
{3, 4} |
difference(-) |
Difference | s1 - s2 |
{1, 2} |
symmetric_difference(^) |
Symmetric difference | s1 ^ s2 |
{1, 2, 5, 6} |
issubset(<=) |
Subset | s1 <= s2 |
False |
issuperset(>=) |
Superset | s1 >= s2 |
True |
Immutable set (frozenset):
Similar to set, but cannot be modified after creation. Elements of a frozenset can be used as elements of other sets or as dictionary keys.
my_frozenset = frozenset([1, 2, 3])