1# Distinguish set and dictionary while creating empty set
2
3# initialize a with {}
4a = {}
5
6# check data type of a
7print(type(a))
8
9# initialize a with set()
10a = set()
11
12# check data type of a
13print(type(a))
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)