A set object is an unordered collection of distinct hashable objects.
In Python, a Set is a built-in data type used to store multiple unique elements in a single variable.
Sets are unordered collections, which means they do not maintain a fixed position for their elements. They also do not allow duplicate values.
Sets are useful when we want to store unique data and perform operations like union, intersection and difference.
1. Creating a Set
A set is created using curly brackets {} or the set() function.
s = {10, 20, 30, 40, 50} print(s) print(type(s)) print(len(s)) Output:
{10, 20, 30, 40, 50} <class 'set'> 5 Explanation:
-
{}is used to create a set with elements. -
type()identifies the data type. -
len()returns the number of elements.
2. Duplicate Elements in Sets
Sets automatically remove duplicate values.
s = {10, 20, 30, 10, 20, 40} print(s) Output:
{10, 20, 30, 40} Explanation: Duplicate elements are automatically removed, so each value appears only once.
3. Creating an Empty Set
To create an empty set, we must use set().
s = set() print(s) print(type(s)) Output:
set() <class 'set'> Note: {} creates an empty dictionary, not an empty set.
4. Adding Elements to a Set
We can use the add() method to insert a single element.
s = {10, 20, 30} s.add(40) print(s) Output:
{10, 20, 30, 40} 5. Adding Multiple Elements Using update()
The update() method adds multiple elements from another iterable.
s = {10, 20, 30} s.update([40, 50, 60]) print(s) Output:
{10, 20, 30, 40, 50, 60} 6. Removing Elements from a Set
Python provides different methods to remove elements.
Using remove():
s = {10, 20, 30, 40} s.remove(20) print(s) Output:
{10, 30, 40} Using discard():
s = {10, 20, 30, 40} s.discard(50) print(s) Output:
{10, 20, 30, 40} Difference:
-
remove()raises a KeyError if the element does not exist. -
discard()does not raise an error if the element is missing.
7. Set Operations
Set operations are one of the most important features of Python sets.
Union ( | )
Union combines all unique elements from two sets.
a = {10, 20, 30} b = {30, 40, 50} print(a | b) Output:
{10, 20, 30, 40, 50} Intersection ( & )
Intersection returns only the common elements.
a = {10, 20, 30} b = {30, 40, 50} print(a & b) Output:
{30} Difference ( - )
Difference returns elements present in the first set but not in the second set.
a = {10, 20, 30} b = {30, 40, 50} print(a - b) Output:
{10, 20} Symmetric Difference ( ^ )
Returns elements that are present in either set, but not in both.
a = {10, 20, 30} b = {30, 40, 50} print(a ^ b) Output:
{10, 20, 40, 50} 8. Checking Elements Using Membership Operators
We can use in and not in to check whether an element exists in a set.
s = {10, 20, 30, 40} print(20 in s) print(50 not in s) Output:
True True 9. Set Methods
Some commonly used set methods are:
| Method | Description |
|---|---|
add() | Adds a single element |
update() | Adds multiple elements |
remove() | Removes an element; raises an error if missing |
discard() | Removes an element without an error if missing |
pop() | Removes and returns an arbitrary element |
clear() | Removes all elements |
copy() | Creates a shallow copy |
union() | Combines two sets |
intersection() | Returns common elements |
difference() | Returns elements in the first set only |
symmetric_difference() | Returns non-common elements |
10. Frozenset in Python
A frozenset is an immutable version of a set. Once created, its elements cannot be added or removed.
s = frozenset([10, 20, 30, 40]) print(s) print(type(s)) Output:
frozenset({10, 20, 30, 40}) <class 'frozenset'> Explanation: Unlike normal sets, frozensets do not support modification methods such as add() and remove().
11. Difference Between List, Tuple and Set
| Feature | List | Tuple | Set |
|---|---|---|---|
| Syntax | [] | () | {} |
| Ordering | Ordered | Ordered | Unordered |
| Mutability | Mutable | Immutable | Mutable |
| Duplicates | Allowed | Allowed | Not allowed |
| Indexing | Supported | Supported | Not supported |
| Usage | Dynamic data | Fixed data | Unique data |
Conclusion
Sets are an important data structure in Python. They help us store unique elements and perform mathematical operations easily.
