Python Set

Python set is immutable.
Python set is unordered values with no duplicates.

empty_set = set() # {} - will not work, because it is a dict

pets = {'dog', 'cat', 'parrot', 'parrot'}
pets_2 = {'dog', 'cat', 'lizzard', 'fish'}

print(pets) # {'parrot', 'cat', 'dog'} (random order, no duplicates)

print(len(pets)) # 3 (no duplicates)

print('Check if element is in the set:')
print('cat' in pets) # True
print('horse' not in pets) # True

print('Add element to the set:')
pets.add('hamster')
print(pets) # {'cat', 'hamster', 'parrot', 'dog'}

print('Get intersection between two sets:')
print(pets.intersection(pets_2)) # {'dog', 'cat'}

print('Get two sets combined (no duplicates):')
print(pets.union(pets_2)) # {'parrot', 'dog', 'hamster', 'cat', 'fish', 'lizzard'}

print('Loop thru items in the set:')
for pet in pets:
    print('Pet item:', pet)

print('Loop thru items in the set with getting element index:')
for pet_index, pet_name in enumerate(pets): # enumerate(pets, start=1) to start from 1
    print('Pet index:', pet_index, ' pet name:', pet_name)

print('Join set items into a string:')
pets_str = '; '.join(pets)
print(pets_str) # dog; cat; parrot

print('Split string into set:')
pets_set = set(pets_str.split('; '))
print(pets_set) # {'cat', 'parrot', 'dog'}

Set operations:

# 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 *