Python set

Basic use of set

1
2
3
4
5
6
7
8
9
10
11
>>>x = set('runoob')
>>>y = set('google')
>>>x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # delete duplicated items
>>>x & y # return the same items in both set
set(['o'])
>>>x | y # return all the items
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>>x - y # like difference
set(['r', 'b', 'u', 'n'])

Practice

1
2
3
4
5
6
7
8
>>>a = set("Google")
a
{'o', 'G', 'g', 'l', 'e'}
>>>b = set("Bob")
b
{'B', 'b', 'o'}
>>>a.difference(b)
{'e', 'G', 'g', 'l'}
1
2
3
4
5
# set A and set B
# deep copy set
C = A.copy()
# add elements in B to A
A.update(B)

How to init

  1. s = set([1,2,3,4,5])
  2. s = {1,2,3,4,5} # it is a set

How to determine an empty set

1
2
3
s = set()
if not s: # if the set is empty
# do sth