0% found this document useful (0 votes)
3 views5 pages

Sets

The document outlines various operations on sets in Python, including adding and deleting elements, performing union and intersection, and understanding subset and superset relationships. It explains methods like add(), remove(), pop(), discard(), and highlights the difference between discard() and remove() in error handling. Additionally, it covers set equality and the concept of frozensets, which are immutable sets.

Uploaded by

afreen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Sets

The document outlines various operations on sets in Python, including adding and deleting elements, performing union and intersection, and understanding subset and superset relationships. It explains methods like add(), remove(), pop(), discard(), and highlights the difference between discard() and remove() in error handling. Additionally, it covers set equality and the concept of frozensets, which are immutable sets.

Uploaded by

afreen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

06-03-24

-----------
SETS:
Operations on Sets:
1. add():
adding elements to set
ex:
#sets
s={10,20,30,40}
type(s)
<class 'set'>
#add
s.add(50)
s.add(60)
s
{40, 10, 50, 20, 60, 30}
2. delete:
deleting elements from a set
remove()
ex:
s.remove(20)
s
{40, 10, 50, 60, 30}
pop()
ex:
s.pop()
40
s
{10, 50, 60, 30}
3. Union:
Combining elements from both sets
ex:
s1={10,20,30}
s2={100,200,300}
s1.union(s2)
{20, 100, 200, 10, 300, 30}
4. Intersection:
Finding the common elements from both the sets
ex:
#INTERSECTION
s1.intersection(s2)
set()
s3={100,1000,500}
s2.intersection(s3)
{100}
5. Set difference:
will give us the remaining elements from first set
excluding the common element
ex:
#set difference
s2-s3
{200, 300}
s3-s2
{1000, 500}

6. superset and subset:


ex:
A={1,2,3}
B={1,2}
B is subset of A
or
A is superset of B
7. Set Equality:
Both sets said to be equal if they have same
elements
ex:
A={1,2,3}
B={1,2,3}
A==B

8. Frozenset():
The set which is readonly or freezed (not
modifiable)

9. discard() : to remove an element from set


remove()
pop()
******
discard() and remove()
discard() will not give any error eventhough the
element to be deleted is not available in set
but remove() will give us error if the deleted
element not there in set
ex:
A
{50, 20, 40, 30}
A.discard(100)
A.remove(100)
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
A.remove(100)
KeyError: 100

6. subset
7. superset
8. equality of sets
9. frozenset

You might also like