Python Set: a quick reference

Sets don’t guarantee the order of the items and are not indexed.

A key point when using sets: they don’t allow repetitions of an item.

Initialization

Empty Set

people = set()

Set with initial values

people = {'Bob', 'Mary'}

Adding in a Set

Use the add() method to add one item.

people.add('Sarah')

Use the update() method do add multiple items at once.

people.update(['Carol', 'Susan'])

Remember, Sets do not allow repetition, so if you add ‘Mary’ again, nothing changes.

people = {'Bob', 'Mary'}

people.add('Mary')

print(people)
{'Bob', 'Mary'}

Updating in a Set

Items in a set are not mutable, you have to either add or delete an item.

Deleting in a Set

To remove Bob from the dictionary:

people = {'Bob', 'Mary'}
people.remove('Bob')
print(people)
{'Mary'}

To delete everybody:

people.clear()

Iterating over sets

Sets are not indexed, to access items, use a loop.

people = {'Bob', 'Mary'}

for person in people:
  print(person)
Bob
Mary

Check if a given item already exists in a set

people = {'Bob', 'Mary'}

if 'Bob' in people:
  print('Bob exists!')
else:
  print('There is no Bob!')