Sets in Python

Set is a mutable datatype in Python.It is written inside the curly braces { } and element are seprated by commas.

Example
se={1,2,3,4,5,6,7,8,9}

Accessing the element value of Sets

In set the element have no index so we can access using loop.

Example
se={11,12,13}
for x in se:
    print(x)
Output
11
12
13

Element exists or not in sets

in operator are used to check element exists or not in sets.

Example
se={11,12,13}
print(12 in se)
Output
True

Add element in sets

add() function are used to add element in sets.

Example
se={11,12,13}
se.add(14)
print(se)
Output
{11,12,13,14}

Add one or more element in sets

update() function are used to add one or more element in sets.

Example
se={11,12,13}
se.update(14,15,16)
print(se)
Output
{11,12,13,14,15,16}

Length of sets

len() function return the length of sets.

Example
se={11,12,13}
print(len(se))
Output
3

Removing the element of sets

remove() and discard() function are used to remove the element of set.

Example
se={11,12,13,14,15,16,17}
print("Using remove function")
se.remove(11)
print(se)
print("Using Discard function")
se.discard(13)
print(se)
Output
Using remove function
{12,13,14,15,16,17}
Using Discard function
{12,14,15,16,17}
Note:

The main difference between discard() and remove() is if the element are going to remove is not present in set then the error occur but in discard() doesen't error occur.

Removing all element of sets:

remove() and clear() function are used to remove all the element of set.

Example
se={11,12,13,14,15,16,17}
print("Before clear")
print(se)
print("After clear")
se.clear()
print(se)
Output
Before clear
{11, 12, 13, 14, 15, 16, 17}
After clear
set()

Murging of two sets

union() function return new set with all items from both sets.

Example
se1={11,12,13}
se2={14,15,16,17}
se3=se1.union(se2))
print(se3)
Output
{11, 12, 13, 14, 15, 16, 17}

update() function are used to murge two sets.

Example
se1={11,12,13}
se2={14,15,16,17}
se1.update(se2))
print(s1)
Output
{11, 12, 13, 14, 15, 16, 17}

Other function and use

function Discription
difference( ) difference between two sets.
discard( ) Remove the specific element.
intersection( ) It return the intersection between the two sets.
isdisjoint( ) It returns two sets having intersection or not.
issubset( ) It returns the given set is subset of another set or not.
symmetric_difference( ) It returns the summetric difference of two sets.
pop( ) Remove the element of the sets