Sets are unordered collections of unique elements in Python. They are similar to lists but with the key difference that they do not allow duplicate elements. Sets are often used for membership testing, removing duplicates from a list, and performing set operations like union, intersection, and difference.
We'll learn about the following topics:
Name | Type in Python | Description | Example |
---|---|---|---|
Sets | set | unordered collection of unique elements. | {10, 'hello'} |
Sets in Python are created using curly braces {}
. You can include elements within the braces, separated by commas.
set1 = {10, "hello", 3.14, True}
type(set1)
set
Also a set can be created with the built-in set()
function.
a = set()
type(a)
set
# We add to sets with the add() method
a.add(89)
a.add('hello')
a.add(2.0)
a
{2.0, 89, 'hello'}
#Create a list with repeated items
lst = [1,1,2,2,3,4,5,6,1,1]
#Cast as set to get unique values
set(lst)
{1, 2, 3, 4, 5, 6}
After converting the list to set with set()
function, only unique items have remained. That's because a set is only concerned with unique elements.
a = {89, 'hello', 2.0}
b = {2.0, 89, 'hello'}
a == b
True
c = set()
c.add('world')
c.add('20')
c.add(89)
|
operator. The union of two sets contains all elements that are in either set or both sets.a | c
{2.0, '20', 89, 'hello', 'world'}
&
operator. The intersection of two sets contains only the elements that are present in both sets.a & c
{89}
a - c
return the set of all elements that are in a but not in c.a - c
{2.0, 'hello'}
^
operator. The symmetric difference of two sets contains the elements that are in either set but not in both sets.a ^ c
{2.0, '20', 'hello', 'world'}
<=
operator is used to check if one set is a subset of another set in Python.d = set()
d.add('hello')
d <= a
True
<
operator in Python. A proper subset is the same as a subset, except that the sets can’t be identical. While a set is considered a subset of itself, it is not a proper subset of itself.a < a
False
>=
operator is used to check if one set is a superset of another. A superset contains all the elements of another set and possibly more.a >= d
True
>
operator is used to check if one set is a proper superset of another set in Python. A proper superset is the same as a superset, except that the sets can’t be identical.a > d
True
Method | Description |
---|---|
union(set) | merge sets and keep unique elements from all sets |
intersection(set) | return the set of elements present in all sets |
difference(set) | x1.difference(x2) return the set of all elements that are in x1 but not in x2 |
symmetric_difference(set) | return the set of all elements in either sets |
isdisjoint(set) | determines whether or not two sets have any elements in common. returns True if they have no elements in common |
issubset(set) | determine whether one set is a subset of the other |
issuperset(set) | set a is considered as the superset of b, if all the elements of set b are the elements of set a |
update(set) | adds any elements in new set that our set does not already have |
intersection_update(set) | retain only elements found in both |
difference_update(set) | it's like difference method except it updates the original set |
symmetric_difference_update(set) | it's like symmetric difference method except it updates the original set |
add(set) | add an item to the set |
remove(m) | remove m from the set |
discard(m) | remove m from the set. However, if m is not in set, discard does nothing instead of raising an exception |
pop() | removes a random element from the set |
clear() | removes all elements from the set |
a.union(c)
{2.0, '20', 89, 'hello', 'world'}
There is a subtle difference between |
operator and .union()
. When you use the |
operator, both operands must be sets. The .union()
method, on the other hand, will take any iterable as an argument, convert it to a set, and then perform the union.
a.union(('a', 'b', 28))
{2.0, 28, 89, 'a', 'b', 'hello'}
a | ('a', 'b', 28)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_10548\564823127.py in <module> ----> 1 a | ('a', 'b', 28) TypeError: unsupported operand type(s) for |: 'set' and 'tuple'
a.intersection(c)
{89}
a.difference(c)
{2.0, 'hello'}
a.symmetric_difference(c)
{2.0, '20', 'hello', 'world'}
a.isdisjoint(c)
False
d.issubset(a)
True
a.issuperset(d)
True
a.update(['a', 'A'])
a
{2.0, 89, 'A', 'a', 'hello'}
#permanently changes the set
a.intersection_update(d)
a
{'hello'}
a.remove('hello')
a
set()
a.discard('hello')
a.remove('hello')
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_10548\918437660.py in <module> ----> 1 a.remove('hello') KeyError: 'hello'
Python provides another built-in type called a frozenset, which is in all respects exactly like a set, except that a frozenset is immutable.
x = frozenset(['a', 45, '78'])
x
frozenset({45, '78', 'a'})
Any attempt to modify a frozenset will fail.
x.add('b')
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_10548\3997461639.py in <module> ----> 1 x.add('b') AttributeError: 'frozenset' object has no attribute 'add'