A set is a collection of unique data. That is, elements of a set cannot be duplicated. For example,
Suppose we want to store information aboutstudent ID cards. Sincestudent ID cardscannot be duplicated, we can use a set.

Create a sentence in Python
In Python, we create sets by placing all elements in curly braces{}
, separated by commas.
A set can have any number of elements and they can be of different types (integer, float, tuple, string, etc.). But a set cannot have mutable elements likeListen, sentences ordictionariesas its elements.
Let's look at an example
# Make a series of integers typestudent_id = {112, 114, 116, 118, 115}print('Student ID:', student_id)# Make a series of strings typevowel_letters = {'a', 'e', 'i', 'o', 'u'}print('Vowel Letters:', vowel_letters)# create a mixed datatype setmixed_set = {'Hello', 101, -2, 'Bye'}print('Mixed datatype set: ', mixed sentence)
Exit
Student ID: {112, 114, 115, 116, 118}Vocal Letters: {'u', 'a', 'e', 'i', 'o'}Mixed Data Type Set: {'hello', ' Goodbye', 101, -2}
In the example above, we created different types of sets by placing all the elements inside the curly brackets{}
.
Note:If you run this code, you may get output in a different order. This is because the set is in no particular order.
Create an empty set in Python
Creating an empty set is a bit tricky. Empty braces{}
will make a blankdictionaryin Python.
To create a set with no elements, we use theSentence()Function with no argument. For example,
# create an empty setempty_set = set()# create an empty dictionaryempty_dictionary = { }# check the data type of empty_setprint('data type of empty_set:', type(empty_set))# check the data type of dictionary_setprint('data type of empty_dictionary' , type (empty_dictionary))
Exit
Data type of empty_set: <class 'set'>Data type of empty_dictionary <class 'dict'>
Here,
- empty set- an empty set created with
Sentence()
- empty_dictionary- an empty dictionary created with
{}
Finally we used itTyp()
Function to know which classempty setAndempty_dictionarybelong.
Duplicate items in one set
Let's see what happens when we try to include duplicate elements in a sentence.
numbers = {2, 4, 6, 6, 2, 8}print(numbers) # {8, 2, 4, 6}
Here we can see that the set does not contain any duplicate elements, since a set cannot contain any duplicates.
Adding and updating set items in Python
Quantities are variable. However, since they are unordered, the indexing has no meaning.
We cannot access or modify an element of a set using indexing or slicing. Set data type does not support it.
Adding elements to a set in Python
In Python we use theadd to()
Method for adding an element to a set. For example,
Zahlen = {21, 34, 54, 12}print('Initial Set:',Zahlen)# using add() methodnumbers.add(32)print('Updated Set:', Numbers)
Exit
First set: {34, 12, 21, 54} Updated set: {32, 34, 12, 21, 54}
In the example above, we created a set namedPay. notice the line
numbers.add(32)
Here,add to()
adds32to our sentence.
Update Python set
TheTo update()
method is used to update the set with elements of other collection types (lists, tuples, sets, etc.). For example,
Companies = {'Lacoste', 'Ralph Lauren'}tech_companies = ['apple', 'google', 'apple']companies.update(tech_companies)print(companies)# Output: {'google', 'apple', ' Lacoste', 'Ralph Lauren'}
Here are all the unique elements oftech_company
are addedcompanies
Sentence.
Remove an element from a set
We use thatdiscard()
method to remove the specified element from a set. For example,
languages = {'Swift', 'Java', 'Python'}print('Initial Set:',languages)# remove 'Java' from a SetremovedValue = languages.discard('Java')print('Set after remove () :', Languages)
Exit
Initial Set: {'Python', 'Swift', 'Java'}Set after remove(): {'Python', 'Swift'}
Here we used thatdiscard()
remove method'Java'
of theLanguagesSentence.
Built-in functions with set
Built-in functions likeat()
,any()
,enumerate()
,len()
,max()
,Minimum()
,sorted ()
,Total()
etc. are commonly used with sentences to perform various tasks.
function | Description |
---|---|
at() | ReturnsTRUE if all elements of the set are true (or if the set is empty). |
any() | ReturnsTRUE if any member of the set is true. If the lot is empty, will be returnedINCORRECT . |
enumerate() | Returns an enumeration object. It contains the index and value for all members of the set as a pair. |
len() | Returns the length (the number of elements) in the set. |
max() | Returns the largest element in the set. |
Minimum() | Returns the smallest element in the set. |
sorted () | Returns a new sorted list of elements in the set (does not sort the set itself). |
Total() | Returns the sum of all elements in the set. |
Iterate over a crowd in Python
fruits = {"apple", "peach", "mango"}# For loop to access each fruit for fruits in fruits: print(fruit)
Exit
MangoPfirsichApfel
Find the number of set elements
We can use thoselen()
Method to get the number of elements present in a set. For example,
even_numbers = {2,4,6,8}print('Set:',even_numbers)# Find number of elements print('Total Elements:', len(even_numbers))
Exit
Theorem: {8, 2, 4, 6} Total elements: 4
Here we used thatlen()
Method to get the number of elements present in a set.
The Python Set Operation
Python Set provides several built-in methods for performing mathematical set operations such as union, intersection, subtraction, and symmetric difference.
Union of two sets
The union of two setsAAndBcontain all elements of setAAndB.

We use that|
operator or theUnion()
-Method to perform set union operation. For example,
# first setA = {1, 3, 5}# second setB = {0, 2, 4}# union operation with |print('Union using |:', A | B)# union operation with union()print perform ('Union using union():', A.union(B))
Exit
Union with |: {0, 1, 2, 3, 4, 5} Union with union(): {0, 1, 2, 3, 4, 5}
note:A|B
AndUnion()
is equivalent toA⋃B
stop operation.
set intersection
The intersection of two setsAAndBcontain the common elements between setAAndB.

In Python we use the&
operator or theOverlap()
-Method to perform set cutting operation. For example,
# first setA = {1, 3, 5}# second setB = {1, 2, 3}# intersection operation with &print('intersection with &:', A & B)# intersection operation with intersection()print( 'intersection with intersection ():', A.Intersection(B))
Exit
Intersection with &: {1, 3}Intersection with intersection(): {1, 3}
note:A&B
AndOverlap()
is equivalent toA⋂B
stop operation.
difference between two sentences
The difference between two sentencesAAndBContain elements of setAthat are not present on the setB.

We use that-
operator or theDifference()
Method to run the difference between two sentences. For example,
# first setA = {2, 3, 5}# second setB = {1, 2, 6}# difference operation with &print('difference with &:', A - B)# difference operation with difference()print( 'difference with difference ():', A.difference(B))
Exit
Difference with &: {3, 5} Difference with Difference(): {3, 5}
note:A-B
AndA. Difference (B)
is equivalent toA-B
stop operation.
Set symmetrical difference
The symmetric difference between two setsAAndBcontains all elements ofAAndBwithout the common elements.

In Python we use the^
operator or theSymmetric_difference()
Method for performing a symmetrical difference between two sentences. For example,
# first setA = {2, 3, 5}# second setB = {1, 2, 6}# difference operation with &print('using ^:', A ^ B)# with symmetric_difference()print('using symmetric_difference( ): ', A.symmetric_difference(B))
Exit
mit ^: {1, 3, 5, 6} mit symmetric_difference(): {1, 3, 5, 6}
Check if two sentences are equal
We can use those==
Operator to check if two sets are equal or not. For example,
# first setA = {1, 3, 5}# second setB = {3, 5, 1}# perform difference operation with &if A == B: print('set A and set B are equal')else: print(' set A and sentence B are not the same')
Exit
Set A and Set B are the same
In the example aboveAAndBhave the same elements, i.e. the condition
if A == B
evaluatesTRUE
. Hence the statementprint('Set A and Set B are the same')
within theIf
is running.
Other Python Set Methods
There are many set methods, some of which we have used above. Here is a list of all the methods available with the Set objects:
Method | Description |
---|---|
add to() | Adds an item to the set |
clear() | Removes all items from the set |
Copy() | Returns a copy of the set |
Difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an item from the set if it is a member. (Do nothing if item is not in set) |
Overlap() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
is disjoint () | ReturnsTRUE if two sets have a zero intersection |
issubset() | ReturnsTRUE if another sentence contains this sentence |
superset() | ReturnsTRUE if this sentence contains another sentence |
Pop() | Removes and returns any set item. Elevatedkey error when the crowd is empty |
removed() | Removes an item from the set. If the element is not a member, a is thrownkey error |
Symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
Union() | Returns the union of sets into a new set |
To update() | Updates the crowd with the union of self and others |