🐍 Advanced Sets
Let's create a blank set and learn by example.
Input
s = Set()
Add Elements to Set
Input
s.add(1)
s.add(2)
s
Output
{1, 2}
This adds new elements to our existing set.
Clear
Input
s.clear()
s
OutputThis empties the set. It deletes all elements.
set()
Copy
Input
s = {1,2,3}
sc = s.copy()
print(s,sc)
OutputThis copies elements from one set to another.
{1, 3, 4} {1, 2, 3}
Difference
Syntax
set1.difference(set2)
Input
s.add(4)
s.difference(sc)
OutputThis returns elements that are not common in the two sets.
{4}
Difference Update
Syntax
set1.difference_update(set2)
Input
s1 = {1,2,3}
s2 = {1,4,5}
s1.difference_update(s2)
s1
OutputThis updates set1 to the difference between set1 and set2.
{2, 3}
Discard
Syntax
set.discard(element)
Input
s = {1,2,3,4}
s.discard(2)
s
OutputThis deletes an element from the set, if that element exists in the set.
{1, 3, 4}
Intersection
Syntax
set1.intersection(set2)
Input
s1 = {1,2,3}
s2 = {2,3,4}
s1.intersection(s2)
Output
{2, 3}
Intersection Update
Syntax
set1.intersection_update(set2)
Input
s1 = {1,2,3}
s2 = {2,3,4}
s1.intersection(s2)
s1
Output
{2, 3}
Is Disjoint?
Syntax
set1.isdisjoint(set2)
Input
s1 = {1,2,3}
s2 = {2,3,4}
s1.isdisjoint(s2)
Output
False
Input
s1 = {1,2,3}
s3 = {4,5,6}
s1.isdisjoint(s3)
OutputIt returns True or False. Returns True if both sets are unique to each other, i.e. no common element in the two sets, else it returns false.
True
Is Subset?
Syntax
set1.issubset(set2)
Input
s1 = {1,2}
s2 = {1,2,3}
s1.issubset(s2)
Output
True
Input
s2.issubset(s1)
OutputIt returns True or False. Returns True if set1 is subset of set2, else it returns false.
False
Is Superset?
Syntax
set1.issuperset(set2)
Input
s1 = {1,2,3}
s2 = {1,2}
s1.issuperset(s2)
Output
True
Input
s2.issuperset(s1)
OutputIt returns True or False. Returns True if set1 is superset of set2, else it returns false.
False
Symmetric Difference?
Syntax
set1.symmetric_difference(set2)
Input
s1 = {1,2,3}
s2 = {1,2,4}
s1.symmetric_difference(s2)
Output
{3, 4}
Union?
Syntax
set1.union(set2)
Input
s1 = {1,2,3}
s2 = {1,2,4}
s1.union(s2)
Output
{1, 2, 3, 4}
Update?
Syntax
set1.update(set2)
Input
s1 = {1,2,3}
s2 = {1,2,4}
s1.update(s2)
s1
Output
{1, 2, 3, 4}
Comments
Post a Comment