
Python Set (Iterate, add, reverse, etc)
A Python set is a set of objects and written with curly braces and comma separators.
s = {'com', 'org', 'net'}
A set can't have a key-value pair like dictionary.
Iterate
s = {1, 2, 7}
for i in s:
print(i)
# 1
# 2
# 7
Add
s = {1, 2, 7}
s.add(4)
print(s) # {1, 2, 4, 7}
A set doesn't change if adding the element that already exists.
s = {1, 2, 7}
s.add(2)
print(s) # {1, 2, 7}
Remove
s = {1, 2, 7}
s.remove(2)
print(s) # {1, 7}
Python raises the KeyError exception if trying to remove the value that doesn't exist.
s = {1, 2, 7}
s.remove(4) # KeyError: 4
This remove an item so is the same as remove
. But some Python programmers love discard
because it doesn't raise the exception.
Empty set
a = {}
b = set()
print(a) # {}
print(b) # set()
print(type(a)) # <class 'dict'>
print(type(b)) # <class 'set'>
Only curly braces represents an empty dictionary. An empty set is defined by set
function.
Comments
Powered by Markdown