Set is a collection in python having capability to contain homogeneous or heterogeneous data items.
When we want to represent a group of data items where duplicates are not allowed and insertion order is not preserved then we use Set.
If we assign duplicate data items, then there is no impact.
In Set we assign data items within a curly bracket.
There are many approaches to represent a Set which is as follows:
When we invoke a set() constructor to create a Set.
s1=set() s1 Output: set() #represents an empty set
#To get all inbuilt functions present in Set dir(s1)
#Add new data items into a Set
s1.add(100)
s1.add(12.34)
s1.add('python')
s1.add(True)
s1.add(100)
s1
Output: {100, 12.34, True, 'python'}
#To find the length of Set s1
len(s1)
Output: 4
#To get required memory size for s1
import sys
print(sys.getsizeof(s1))
Output: 224
#To retrieve all data items from set s1
for k in s1:
print(k)
Output:
True
python
100
12.34
#Another approach to represent a set
s2=set(['orange','banana','cherry','apple'])
s2
Output: {'apple', 'banana', 'cherry', 'orange'}
Here within a set() function, we have taken a list of data items.
#Remove a data item from set s2.discard('apple') s2 Output: {'banana', 'cherry', 'orange'} s2.remove('banana') s2 Output: {'cherry', 'orange'} s2.pop() s2 Output: {'orange'}
Here there are 3 functions like discard(), remove(), pop() that we can use to remove a data item from a Set.
#To copy all data items from s1 to another new set using copy() function
s3=s1.copy()
s3
Output: {100, 12.34, True, 'python'}
#To clear all data items from set s3 using clear() function
s3.clear()
Output: set() #empty set
Another approach to represent a Set(that is directly we can assign data items within a curly bracket).
s4={10,20,30,40,50}
s5={50,60,70,80}
print(s4)
print(s5)
Output:
{40, 10, 50, 20, 30}
{80, 50, 60, 70}
#To perform union operation using union() function
s4.union(s5)
Output: {10, 20, 30, 40, 50, 60, 70, 80}
s4.intersection(s5)
Output: {50}
#issubset()
issubset(...) method of builtins.set instance
Report whether another set contains this set.
s4.issubset(s5)
Output: False
#issuperset()
issuperset(...) method of builtins.set instance
Report whether this set contains another set.
s4.issuperset(s5)
Output: False
#update()
update(...) method of builtins.set instance
Update a set with the union of itself and others.
s4.update(s5)
s4
Output: {10, 20, 30, 40, 50, 60, 70, 80}
#symmetric_difference()
s4.symmetric_difference(s5)
Output: set()
#symmetric_difference_update()
s4.symmetric_difference_update(s5)
s4
Output: {10, 20, 30, 40, 50, 60, 70, 80}
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc