Python - Set

python set

Python set is similar to a list, but it only holds unique values, is unordered and its elements are immutable.


my_set = { 'python', (1, 2), True, 'lisp' }

You can't store mutable data in sets.


Add Set Elements

To add a set element, you have two options:

x = {}
x.add(1)
x.update([1, 2, 4])

Remove Set Elements

To remove a set element, you have two options:

x = { 'bulbasaur', 'charmander', 'squirtle' }
y = x.pop() # 'squirtle'
x.remove('bulbasaur')
x.discard('charmander')

Join Sets

To join sets, you have four options:

x = { 1, 2, 3, 4, 5 }
y = { 1, 3, 5, 8, 9, 10 }

print(x.union(y)) # {1, 2, 3, 4, 5, 8, 9, 10}
print(x.intersection(y)) # {1, 3, 5}
print(x.difference(y)) # {2, 4}
print(x.symmetric_difference(y)) # {2, 4, 8, 9, 10}

Set Length

To obtain the length of a set use len(x).

x = {"A", "B", "C", 'a', 'b', 'c'}
print(len(x)) # 6