Python Set

# Sets store ... well sets
empty_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
some_set = {1, 1, 2, 2, 3, 4}  # some_set is now {1, 2, 3, 4}
 
# Similar to keys of a dictionary, elements of a set have to be immutable.
invalid_set = {[1], 1}  # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
 
# Can set new variables to a set
filled_set = some_set
 
# Add one more item to the set
filled_set.add(5)  # filled_set is now {1, 2, 3, 4, 5}
 
# Do set intersection with &
other_set = {3, 4, 5, 6}
filled_set & other_set  # => {3, 4, 5}
 
# Do set union with |
filled_set | other_set  # => {1, 2, 3, 4, 5, 6}
 
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5}  # => {1, 4}
 
# Do set symmetric difference with ^
{1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}
 
# Check if set on the left is a superset of set on the right
{1, 2} >= {1, 2, 3} # => False
 
# Check if set on the left is a subset of set on the right
{1, 2} <= {1, 2, 3} # => True
 
# Check for existence in a set with in
2 in filled_set   # => True
10 in filled_set  # => False

Leave a Reply

Your email address will not be published. Required fields are marked *