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:
add(x)
- add the element.update(iterable)
- update set using a iterable.
x = {}
x.add(1)
x.update([1, 2, 4])
Remove Set Elements
To remove a set element, you have two options:
remove(element)
- remove the element, will raise an error if the specified element is not present in the set.discard(element)
- discard the element, will not raise an error if the element is not found.pop()
- remove the last element and returns it reference.
x = { 'bulbasaur', 'charmander', 'squirtle' }
y = x.pop() # 'squirtle'
x.remove('bulbasaur')
x.discard('charmander')
Join Sets
To join sets, you have four options:
union(iterable)
- returns a set with the union of the set and the iterable.intersection(iterable)
- returns a set with the intersection between the set and the iterable.difference(iterable)
- returns a set with the difference between the set and the iterable.symmetric_difference(iterable)
- returns a set with elements in either the set or other but not both.
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