Python Sets
Sets in Python
A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add and remove elements, but every element must be unique (no duplicates are allowed). Sets are used when you want to store distinct items and perform operations like union, intersection, and difference.
Key Features of Sets:
- Unordered: Sets do not maintain the order of elements.
- Unique Elements: All elements in a set must be unique. If you add a duplicate, it will be automatically removed.
- Mutable: You can add or remove elements from a set.
- Unindexed: Since sets are unordered, you cannot access elements by index.
Set Syntax:
Sets are defined using curly braces {}
or the set()
function.
Example: Creating and Printing a Set
Adding Elements to a Set:
You can add elements to a set using the add()
method.
Removing Elements from a Set:
Elements can be removed using the remove()
or discard()
methods. The difference is that remove()
will raise an error if the element is not found, while discard()
will not.
You can also remove and return an arbitrary element using pop()
, and remove all elements using clear()
.
Set Operations:
Python sets support various mathematical set operations such as union, intersection, difference, and symmetric difference.
- Union (
|
): Combines all elements from two sets (removes duplicates).
- Intersection (
&
): Returns only the elements common to both sets.
- Difference (
-
): Returns the elements that are in the first set but not in the second.
- Symmetric Difference (
^
): Returns elements that are in either of the sets but not in both.
Set Methods:
add(x)
: Adds an elementx
to the set.remove(x)
: Removesx
from the set (raises an error ifx
is not in the set).discard(x)
: Removesx
from the set (does nothing ifx
is not in the set).pop()
: Removes and returns an arbitrary element from the set.clear()
: Removes all elements from the set.union(set)
: Returns a new set containing all elements from both sets.intersection(set)
: Returns a new set containing elements common to both sets.difference(set)
: Returns a new set with elements from the first set that are not in the second set.symmetric_difference(set)
: Returns a new set with elements that are in either set, but not both.
Set Comprehension:
You can create sets using set comprehension, similar to list comprehension.
Checking Membership:
You can check if an element exists in a set using the in
keyword.
Frozen Sets:
A frozenset is an immutable version of a set. Once a frozenset is created, you cannot add or remove elements from it. Frozensets are useful when you need an immutable set, such as using sets as keys in a dictionary.
Summary:
- Sets are unordered collections of unique elements, used when you need to store distinct items.
- They support set operations like union, intersection, and difference.
- Frozen sets are immutable sets that cannot be modified once created.