1# You can't create a set like this in Python
2my_set = {} # ---- This is a Dictionary/Hashmap
3
4# To create a empty set you have to use the built in method:
5my_set = set() # Correct!
6
7
8set_example = {1,3,2,5,3,6}
9print(set_example)
10
11# OUTPUT
12# {1,3,2,5,6} ---- Sets do not contain duplicates and are unordered
13
1>>> A = {0, 2, 4, 6, 8};
2>>> B = {1, 2, 3, 4, 5};
3
4>>> print("Union :", A | B)
5Union : {0, 1, 2, 3, 4, 5, 6, 8}
6
7>>> print("Intersection :", A & B)
8Intersection : {2, 4}
9
10>>> print("Difference :", A - B)
11Difference : {0, 8, 6}
12
13# elements not present both sets
14>>> print("Symmetric difference :", A ^ B)
15Symmetric difference : {0, 1, 3, 5, 6, 8}
16
1The simplest way to create set is:
21. from list
3code:
4 s = [1,2,3]
5 set = set(s)
6 print(set)
7
82. s,add() method
9code:
10 set.add(1)
11 set.add(2)
12 set.remove(2)
13 print(set) // 1
14
153. Set conatins unique elements
1# A set contains unique elements of which the order is not important
2s = set()
3s.add(1)
4s.add(2)
5s.remove(1)
6print(s)
7# Can also be created from a list (or some other data structures)
8num_list = [1,2,3]
9set_from_list = set(num_list)
1# Create a set
2seta = {5,10,3,15,2,20}
3# Or
4setb = set([5, 10, 3, 15, 2, 20])
5
6# Find the length use len()
7print(len(setb))
1set_example = {1, 2, 3, 4, 5, 5, 5}
2
3print(set_example)
4
5# OUTPUT
6# {1, 2, 3, 4, 5} ----- Does not print repetitions