Register Login

Python Sets

Updated May 17, 2022

Set is a collection of well-defined objects as per mathematical definition. Set in python is the same as in mathematics. Set is a Build in Data Type in python to store different unique, iterable data types in the unordered form. Set can have elements of many data types such as int, string, tuple, etc.

Set is based on the hashing concept which makes it optimized in the search operation. So, it is used in case we have to perform many search operations on the collection of data. Set data structure is used when we want each element to be unique in a large collection of data.

x = {1,2.3, "py", (1,2,3)}
print(x)

Output:

Properties of Set Data Type:

Set follow three properties:

  1. Unordered
  2. Unique
  3. Immutable
  1. Set store the element in an unordered manner such that no direct access to the element is possible. We use an iterator to iterate over all elements of the set.
  2. Set store the element uniquely. No duplicate element is allowed. If we try to insert an element that is already present in the set then the element will not insert and remain as it is. The frequency of each element is set as one.
  3. Each element in the set is immutable which means elements can not be changed. Hence sets can contain elements of Datatype int, string, Tuple, etc but can not contain List, sets, dictionaries. set elements are immutable but the set is mutable which means we can insert and delete elements from the set.

Program:

x = {4, 2, 2, 6, 1, 0, 6}
print(x)
y = {1, 2, [3, 4], 5}

Output:

Initialization of set:

Set can be initialized in two ways:

  1. By set() Constructor
  2. By curly {} braces

By set() Constructor

A set can be created with a set() constructor by passing an iterable element such as list, string, etc in the method.

Syntax:

variable = set(iterable element)

By Curly {} brackets:

A set can be created bypassing elements inside curly braces separated by a comma. These Elements can be any Immutable data type such as int, string, bool, tuple, etc but can not be List, sets, dictionaries.

Syntax:

variable = {element1, element2,..}

Program:

# Initialization of set by set() Constructor
x = set("python")
print('By set() constructor: ', x)

# Initialization of set by curly {}brackets
y={'y', 'n', 't', 'p', 'h', 'o'}
print('curly {}brackets: ', y) 

Output:

Traversal the set:

Set can be traversed with help of (for in) keywords. As no direct access to the element is possible therefore only linear traversal is possible in the set.

Syntax:

for element in set:
    print(element)

Program:

# Initialization of set x
x={'p','h','t','n','o'}

# Traversal the set with for loop
for y in x:
    print(y)

Output:

Insertion into the set:

Insertion into the set can be done by five method:

  1.   add()
  2.   update()
  3.   intersection_update ()
  4.   difference_update()
  5.   symmetric_difference_update()

Add()

Add() method is used to add a unique element into the set bypassing the element into the add method. The element can be any Immutable data type such as int, string, tuple, etc.

Syntax:

set.add(element)

Update()

Update() method is used to add multiple elements into the set. Multiple elements can be in form of iterable data types such as set, list, tuple, string, etc

Syntax:

set1.update(list)

Program:

# Initialization of set x
x = {2,4,6}
print('Set x: ', x)

# add 8 to the set x
x.add(8)
print('Add value to set x: ', x)

# Initialization set y
y={2,3,4,5}
print('Set y: ', y)

# Update y to set x
x.update(y)

print('Set y: ', y)
print('Set x after update: ', x)

Output:

Intersection_update

Intersection_update updates the first set by tacking common elements from both sets.

Syntax:

set1.intersection_update(set2)

Difference_update:

Difference_update  updates the first set by removing the common element of two sets from the first set.

Syntax:

set1.difference_update(set2)

Symmetric_difference

Symmetric_difference updates the first set by tacking elements that are not common in both sets.

Syntax:

set1.symmetric_difference_update(set2)

Program:

# Initialization of set x & y
x={1,2,3,4}
y={3,4,5,6}
print('Set x: ', x)
print('Set y: ', y)

# Intersection of x & y
x.intersection_update(y)
print('Set x after intersection: ', x)
print('Set y after intersection: ', y)

# Difference of x and y
x={1,2,3,4}
x.difference_update(y)
print('Set x after difference: ', x)
print('Set y after difference: ', y)

# Symmetric difference of x and y
x={1,2,3,4}
x.symmetric_difference_update(y)
print('Set x after symmetric difference: ', x)
print('Set y after symmetric difference: ', y)

Output:

Deletion from the set

Deletion operation on the set can be performed by these four methods:

  1. remove
  2. discard
  3. pop
  4. clear

Remove

Remove method removes an element from the set which is passed in the method from the set. If the element is not present in the set then it raises an error message.

Syntax:

set.remove(element)

Discard

Discard method removes an element from the set which is passed in the method from the set. If the element is not present in the set then it gives no error message.

Syntax:

set.discard(element) 

pop()

pop() gives the last element of the set by removing the last element from the set.

Syntax:

variable = set.pop()

clear()

clear() method removes all the elements of the set (set becomes null).

Syntax:

set.clear()

Program:

# Initialization of set x
x={'Python','Java','PHP','Angular'}
print('Set x: ', x)
x.remove('Java')
print('Set x after remove: ', x)

x.discard('PHP')
print('Set x after discard: ', x)

# Initialization set x
x={1,2,"py"}
print('Print set x: ', x)
# pop last element from the set x
z=x.pop()
print('Print first element of set x: ', z)

# clear all element from set
x.clear()
print('Print set x after clear: ', x)

Output:

Set operation:

We can perform the following mathematical operation on the set:

  1. union  
  2. intersection
  3. difference   
  4.  symmetric_difference
  5.  issubset
  6.  isdisjoint

Union()

Union() method gives the combination of the elements from both sets.

Syntax:

newSet=set1.union(set2)

Intersection

Intersection method gives the common elements from both sets.

Syntax:

newSet=set1.intersection (set2)

Difference

Difference method gives all elements which are in sets are not common between.

Syntax:

newSet=set1.difference (set2)

Symmetric difference

Symmetric method gives the elements which are in both sets but are not common.

Syntax:

newSet=set1.symmetric_difference(set2)

Program:

# Initialization of set x and y
x={1,2,3,4}
y={3,4,5,6}

# Union of set x and y
z=x.union(y)
print('union of x and y: ', z)

# intersection of x and y
z=x.intersection(y)
print('intersection of set x and y: ', z)

# difference of set x and y
z=x.difference(y)
print('difference of set x and y', z)

# symmetric_difference of set x and y
z=x.symmetric_difference(y)
print('symmetric_difference of set x and y: ',z)

Output:

Issubset

Issubset checks if the first set is a subset of another set.

Syntax:

bool variable=set1.issubset(set2)

Isdisjoint

Isdisjoint checks if there is no common element between two sets.

Syntax:

bool variable=set1.isdisjoint(set2)

Program:

# Initialization of set x and y
x={1,2}
y={1,2,3,4}

# check if set x is subsite of y
z=x.issubset(y)
print('Check if x is subset of y: ', z)

# Initialization set x and y
x={1,2}
y={3,4}

# Check if set x and y are disjoint
z=x.isdisjoint(y)
print('Check if set x and y are disjoint:', z)

Output:

Operator with set:

There are many operators which can be used with sets . Some of them are as follow:

== Checks if two sets are equal or have the same elements.
!= Checks if two sets are not equal or have different elements.
<= Checks if the first set is a subset of another set.
< Checks if the first set is a proper subset of another set.
>= Checks if the first set is a superset of another set.
> Checks if the first set is a proper superset of another set.
& This operator takes the intersection of two sets.
 | This operator takes the union of two sets.
- This operator takes the difference of two sets.
^ This operator takes the Symmetric Difference of two sets.

Program

# Initialization of set x and y
x = {'a','b','c'}
y = {'a','b','c'}
print('Set x: ', x)
print('Set y: ', y)

# Operator with set
print('Set x == y: ', x==y)

print('Set x != y: ', x != y)

# Initialization of set x and y
x = {1,2}
y = {1,2,3,4}
print('Set x: ', x)
print('Set y: ', y)

print('Set x <= y: ', x <= y)

print('Set x < y: ', x < y)

# Initialization of set x and y
x = {1,2,3,4}
y = {1,2,3}

print('Set x superset y:', x >= y)
print('Set x proper superset y:', x > y)
print('Intersection  x & y:', x & y)
print('Union of x & y:', x | y)
print('Difference of x & y:', x - y)
print('Symmetric Difference of  x & y:', x ^ y)

Output:

 

Some Build in Methods:

There is some built in function in the set:

Copy () To shallow copy a set to another set.
in Check if an element is in the set.
not in Check if an element is not in the set.
 len () Find the number of elements in the set.
max () Find the max element in the set.
min () Find the minimum element in the set.
sorted () Sort the elements of the set.
sum () Find the sum of elements of the set.
enumerate () Convert set to enumerating object.
all () Check if all the iterable elements of the set are true.
 any () Check if any of the iterable elements of the set is true.

Program:

# Initialization of set x 
x={1,2,3,4}

# copy set x to set z
z=x.copy()

print('Copy set x to set z: ', z)

print('Print length of set z: ', )
len(z)

print('Print min of set z: ')
min(z)

print('Print max of set z: ')
max(z)

# Sort set z
sorted(z)
y=enumerate(z)
for i,j in y:
    print(i,j)
x={0,1,0,1}
all(x)
any(x)

Output:

Frozenset concept:

Frozenset () is the inbuilt Data Type-like set but is immutable which means no insertion and deletion operation possible with the set.

Syntax:

variable = frozenset(elements)

Program

x=frozenset((1,2,3,4))
print(x)
frozenset({1, 2, 3, 4})
x.add(5)
x.pop()

Output:

Conclusion:

Therefore, it is highly recommended to use a python set data type while programming because it increases the searching time complexity and with the large collection of inbuilt functions in the set it increases coding efficiency.


×