Set is a mutable datatype in Python.It is written inside the curly braces { } and element are seprated by commas.
Examplese={1,2,3,4,5,6,7,8,9}
In set the element have no index so we can access using loop.
Examplese={11,12,13} for x in se: print(x)Output
11 12 13
in operator are used to check element exists or not in sets.
Examplese={11,12,13} print(12 in se)Output
True
add() function are used to add element in sets.
Examplese={11,12,13} se.add(14) print(se)Output
{11,12,13,14}
update() function are used to add one or more element in sets.
Examplese={11,12,13} se.update(14,15,16) print(se)Output
{11,12,13,14,15,16}
len() function return the length of sets.
Examplese={11,12,13} print(len(se))Output
3
remove() and discard() function are used to remove the element of set.
Examplese={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.
remove() and clear() function are used to remove all the element of set.
Examplese={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()
union() function return new set with all items from both sets.
Examplese1={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.
Examplese1={11,12,13} se2={14,15,16,17} se1.update(se2)) print(s1)Output
{11, 12, 13, 14, 15, 16, 17}
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 |