DEV Community

Keerti Sadana S
Keerti Sadana S

Posted on

PYTHON - SET

-> A Set in Python is a collection of unique items.
->It is an unordered collection that does not allow duplicate entries. Sets are primarily used for membership testing and eliminating duplicates from a sequence.
-> It is mutable.
-> Set can be created by set() and {v1,v2,...vn}.
-> {} means a dictionary.

Mathematical Operations:
union, intersection, difference

s1 = {10,20,30,40}
s2 = {30,40,70,80}
print(s1.union(s2))
print(s1 | s2)

print(s1.intersection(s2))
print(s1 & s2)

print(s1.difference(s2))
print(s1 - s2)

print(s1.symmetric_difference(s2))
print(s1 ^ s2)
Enter fullscreen mode Exit fullscreen mode

Output:
{70, 40, 10, 80, 20, 30}
{70, 40, 10, 80, 20, 30}
{40, 30}
{40, 30}
{10, 20}
{10, 20}
{70, 10, 80, 20}
{70, 10, 80, 20}

remove() vs clear() vs pop():

s = {'Hi', True, 5}
s.remove('Hi')
print(s)
print(s.pop())
print(s)
s.clear()
print(s)
Enter fullscreen mode Exit fullscreen mode

Output:
{5, True}
5
{True}
set()

discard():
-> In Python, the discard() method removes a specified element from a set.
-> If the element is not found, it won't return an error

s = {'Hi', 10,20, True}
s.remove('Hi')
print(s)
s.discard('Hello')
print(s)
Enter fullscreen mode Exit fullscreen mode

Output:
{True, 10, 20}
{True, 10, 20}

Top comments (0)