Explore

Edit

Edit

# Sets In Python With Examples | FACE Prep

Published on 09 Mar 2020

Sets in Python are a collection of unordered and unindexed elements of different data types. Every element in a set should be unique (no duplicates allowed) & immutable (cannot be modified or changed). Since the elements in the set are unordered and unindexed, we cannot assure that the output will be printed in the same way in which the elements are stored in a set.

Before we look at the operations of sets, lets first understand this.........

## How Are Sets Better Than Other DataTypes?

Sets will not contain multiple occurrences of the same element, they are very useful in removing duplicate elements from a list or a tuple. Also, they are useful in computing mathematical notations such as union, intersection, etc.

## How to Create Sets in Python

A set can be created by placing the comma-separated elements inside curly brackets { } or it can simply be created using the set () method. Also,Tuples, Lists, Dictionaries are mutable data types and hence elements of these data types cannot be a part of a set.

THE WRONG METHOD:

#creating an empty set
set1 = {}
print(set1)
print(type(set1))

Output
{}
<class 'dict'>


Explanation: As you can see, the above empty set is of dictionary datatype. This is because, whenever we try to create an empty set using curly brackets as shown in the above code, the compiler will create an empty dictionary instead of an empty set. So to create an empty set, you need to use the set () method as shown below.

THE RIGHT METHOD:

#creating an empty set
set1 = set()
print(set1)
print(type(set1))

#creating a set with elements of different data types
set1 = {20, 30.45, "Python"}
print(set1)
print(type(set1))

﻿Output:
set()
<class 'set'>
{20, 30.45, 'Python'}
<class 'set'>


Since the elements in a set are unordered and unindexed, they do not get stored or printed in the order in which they are initialized. For instance,

set1 = {"Welcome", "to", "Python", "course"}
print(set1)

Output:
{'course', 'Python', 'Welcome', 'to'} #For the first time
{'to', 'Welcome', 'Python', 'course'}#For thesecond time
{'to', 'course', 'Python', 'welcome'}#For thethird time


## How to Add Elements to a Set

Although the elements in a set are immutable, since set itself is a mutable data type, adding or removing elements from a set is feasible.

This method allows us to add elements to a set. For example,

set1 = set() # creating an empty set

# adding two elements into the set
print(set1)

Output
{20, 'Hai'}


### b) Using update() method

This method is used to add multiple elements to a new set or to an existing set.In simple, it is also used to concatenate or join two or more sets.

#adding multiple elements to a new set
set1 = set() # creating an empty set
set1.update({20, 30.45, "FACE Prep", "Python"})
print(set1)

#adding multiple elements to an existing set
set2 = {"Welcome", "to", "Python", "course"}
set2.update({20, 30.45, "Hi"})
print(set2)

Output:
{'FACE Prep', 20, 'Python', 30.45}
{'Python', 'Hi', 20, 30.45, 'Welcome', 'course', 'to'}


## How to Change/Modify Elements of a Set

As we know, the elements in a set cannot be changed once initialized. So, the compiler throws an error whenever you try to modify/update a particular element.

#updating/modifying an element
set1 = {"Welcome", "to", "Python", "course"}
set1[1] = "everyone to"
print(set1)

Output
Traceback (most recent call last):
File "/home/980dfee6166985e937eaeeaa22cf7d78.py", line 2, in <module>
set1[1] = "everyone to"
TypeError: 'set' object does not support item assignment


## How to Access Elements in a Set

Since elements in a set are unordered and unindexed, we cannot determine the index values of the elements. Hence, accessing elements is practically not possible in the case of a set.

#accessing elements of a set
set1 = {"Welcome", "to", "Python", "course"}
print(set1[1])

Output
Traceback (most recent call last):
File "/home/105aea425424b9da32c25754ac79c385.py", line 2, in <module>
print(set1[1])
TypeError: 'set' object does not support indexing


However, we can access the elements in a set using for loop (for loop will be discussed later, but for now, remember that this can be done using for loop)

set1 = {"Welcome", "to", "Python", "course"}
for res in set1:
print (res)

Output
to
Python
Welcome
course


## How to Delete Elements from a Set

### a) Using remove() method

remove () method can be used to remove a specific element from the set. For example, in the below code, we are trying to remove the element "course" from set1.

#deleting element of a set
set1 = {"Welcome", "to", "Python", "course"}
set1.remove("course")
print(set1)

Output
{'Welcome', 'to', 'Python'}


Note: In case the element to be deleted is not present in the set, then the compiler throws an error.

### b) Using discard () method

This method works the same as that of the remove() method. But, unlike the remove () method, this method does not throw an error when an out of set element is said to be deleted. Rather, it simply returns and prints the remaining elements of the set. For instance,

#deleting an element from a set
set1 = {"Welcome", "to", "Python", "course"}
set1.discard(20) #20 is not an element in set1
print(set1)

Output
{'course', 'Python', 'to', 'Welcome'}


### c) Using pop() method

This method always removes the last element from a set. But, since a set is unordered and unindexed, we will never know the last element i.e we will never know which element gets deleted from the set.

#deleting the last element
set1 = {"Welcome", "to", "Python", "course"}
print(set1.pop())
print(set1)

Output:
course
{'Welcome', 'Python', 'to'}


### d) Using clear() method

This method simply deletes all the elements from a set. Hence this method always returns an empty set.

#deleting all the elements
set1 = {"Welcome", "to", "Python", "course"}
set1.clear()
print(set1)

Output
set()


### e) Using del() method

Unlike the other methods, this method doesn't delete the elements of a set. Rather, it deletes the entire set.

#deleting a set
set1 = {"Welcome", "to", "Python", "course"}
del set1
print(set1)

Output
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(set1)
NameError: name 'set1' is not defined


## Standard Set Operations

Some of the standard set operations are:

OperationSymbol or RepresentationOperation Description
Union
A | B
A.union(B)
Returns a set of elements which is the union of sets A and B.
Update
A |= B
A.update(B)
Returns a set with the elements of B added to the elements of set A.
Intersection
A & B
A.intersection(B)
Returns a new set with elements present in both A & B.
Intersection Update
A &= B
A.intersection_update(B)
Updates the elements of set A with elements present in both the sets A & B.
Difference
A – B
A.difference(B)
Returns a set with elements that are present in A but not in B.
Difference Update
A -= B
A.difference_update(B)
Returns the elements of set A, where all elements of B are removed from the set A.
Symmetric Difference
A ^ B
A.symmetric_difference(B)
Returns a set with elements belonging to either A or B
Symmetric Difference Update
A ^= B
A.symmetric_difference_update(B)
Considers the common elements in set A & B, these common elements in set A will be replaced by elements belonging to either A or B.
Issubset
A <= B
A.issubset(B)
Returns true if A is a subset of B.
Issuperset
A >= B
A.issuperset(B)
Returns true if B is a subset of A.