Python Sets: Create A Set in Python
Python Sets: Create A Set in Python
A set is a collection of unique data, meaning that elements within a set cannot be
duplicated.
For instance, if we need to store information about student IDs, a set is suitable since
student IDs cannot have duplicates.
In the above example, we have created different types of sets by placing all the
elements inside the curly braces {} .
Note: When you run this code, you might get output in a different order. This is
because the set has no particular order.
Output
Here,
empty_set - an empty set created using set()
Here, we can see there are no duplicate items in the set as a set cannot contain
duplicates.
Output
numbers.add(32)
Here, all the unique elements of tech_companies are added to the companies set.
Output
Here, we have used the discard() method to remove 'Java' from the languages set.
Built-in Functions with Set
Here are some of the popular built-in functions that allow us to perform different
operations on a set.
Function Description
Returns True if all elements of the set are true (or if the set is
all()
empty).
Returns True if any element of the set is true. If the set is empty,
any()
returns False .
Returns an enumerate object. It contains the index and value for all the
enumerate()
items of the set as a pair.
Returns a new sorted list from elements in the set(does not sort the set
sorted()
itself).
Output
Mango
Peach
Apple
Output
Set: {8, 2, 4, 6}
Total Elements: 4
Here, we have used the len() method to find the number of elements present in a Set.
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Output
Set Intersection
The intersection of two sets A and B include the common elements between set A and B .
Set Intersection in Python
In Python, we use the & operator or the intersection() method to perform the set
intersection operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
# perform intersection operation using &
print('Intersection using &:', A & B)
# perform intersection operation using intersection()
print('Intersection using intersection():', A.intersection(B))
Output
Output
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
Output
In the above example, A and B have the same elements, so the condition
if A == B
evaluates to True . Hence, the statement print('Set A and Set B are equal') inside
the if is executed.
Method Description
update() Updates the set with the union of itself and others