Python Sets
Python Sets
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.
Create a Set in Python
In Python, we create sets by placing all the elements inside curly braces {}, separated by
commas.
A set can have any number of items and they may be of different types (integer, float, tuple,
string, etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
Output
Student ID: {112, 114, 115, 116, 118}
Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}
Note: When you run this code, you might get output in a different order. This is because the
set has no particular order.
Create an Empty Set in Python
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python.
To make a set without any elements, we use the set() function without any argument.
# create an empty set
empty_set = set()
Output
Data type of empty_set: <class 'set'>
Data type of empty_dictionary: <class 'dict'>
Duplicate Items in a Set
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.
print('Initial Set:',numbers)
print(companies)
print('Initial Set:',languages)
Output
Set: {8, 2, 4, 6} Total Elements: 4
Python Set Operations
Union of Two Sets
The union of two sets A and B includes all the elements of sets A and B.
We use the | operator or the union() method to perform the set union operation
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Output
Union using |: {0, 1, 2, 3, 4, 5}
In Python, we use the & operator or the intersection() method to perform the set intersection
operation
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
Output
Intersection using &: {1, 3}
# second set
B = {1, 2, 6}
Output
# second set
B = {1, 2, 6}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Output
using ^: {1, 3, 5, 6}