13. SetData Structure
13. SetData Structure
1. s={10,20,30,40}
2. print(s)
3. print(type(s))
4.
5. Output
6. {40, 10, 20, 30}
7. <class 'set'>
Eg 1:
1. l = [10,20,30,40,10,20,10]
2. s=set(l)
3. print(s) # {40, 10, 20, 30}
Eg 2:
1. s=set(range(5))
2. print(s) #{0, 1, 2, 3, 4}
Eg:
1. s={}
2. print(s)
3. print(type(s))
4.
5. Output
6. {}
7. <class 'dict'>
Eg:
1. s=set()
2. print(s)
3. print(type(s))
4.
5. Output
6. set()
7. <class 'set'>
set Eg:
1. s={10,20,30}
2. s.add(40);
3. print(s) #{40, 10, 20, 30}
2. update(x,y,z):
Eg:
1. s={10,20,30}
2. l=[40,50,60,10]
3. s.update(l,range(5))
4. print(s)
5.
6. Output
7. {0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
We can use add() to add individual item to the Set,where as we can use update()
function to add multiple items to Set.
add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects.
1. s.add(10)
2. s.add(10,20,30) TypeError: add() takes exactly one argument (3 given)
3. s.update(10) TypeError: 'int' object is not
iterable 4. s.update(range(1,10,2),range(0,10,2))
3. copy():
s={10,20,30}
s1=s.copy()
print(s1)
4. pop():
set. Eg:
1. s={40,10,30,20}
2. print(s)
3. print(s.pop())
5.
6. Output
7. {40, 10, 20, 30}
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50
6. discard(x):
s={10,20,30}
s.discard(10)
print(s) ===>{20,
30} s.discard(50)
print(s) ==>{20, 30}
7. clear():
1. s={10,20,30}
2. print(s)
3. s.clear()
5.
6. Output
7. {10, 20, 30}
Mathematical operations on the Set:
1.union():
x.union(y) ==>We can use this function to return all elements present in both
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}
2. intersection():
x.intersection(y) or x&y
y Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}
3. difference():
x.difference(y) or x-y
returns the elements present in x but not
in y Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10, 20}
print(y-x) #{50, 60}
4.symmetric_difference():
x. symmetric_difference(y) or x^y
both Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y)) #{10, 50, 20, 60}
print(x^y) #{10, 50, 20, 60}
1. s=set("durga")
2. print(s)
3. print('d' in s)
5.
6. Output
7. {'u', 'g', 'r', 'd', 'a'}
9. True
Set Comprehension:
Set comprehension is possible.
s={x*x for x in
range(5)} print(s) #{0, 1,
4, 9, 16}
s={2**x for x in
range(2,10,2)} print(s)
#{16, 256, 64,
4}
Approach-1:
Approach-2:
5. l1.append(x)
6. print(l1)
7.
9. D:\Python_classes>py test.py
10. Enter List of values: [10,20,30,10,20,40]
11. [10, 20, 30, 40]