Set

Example of a set

Sets, like lists, are used to store multiple objects in a single variable. However, sets have interesting properties: they only contain unique items and are unordered.

Creating sets

To create an empty set, use the set() constructor method:

Example of an empty set

You can also initialize sets with values simply by using curly brackets. This is similar to a dictionary except you are providing a single value instead of a key value pair.

Example of an non-empty set

Warning

You cannot create an empty set using curly brackets, Python will assume you are creating a dictionary!

Adding to a set

O(1)

Adding to a set is easy, just use the add() method:

Example of adding to a set

Removing an item from a set

O(1)

You can remove an item from a set in two ways:

  • remove() removes the element if it exists, otherwise throws an error
  • discard() removes the element if it exists

For a smoother interview experience, we recommend using discard() to avoid interruptions caused by exceptions. However, in general it's best practice to appropriately throw, catch, and handle exceptions.

Example of removing an item from a set

Checking if an object exists in a set

O(1)

An advantage of sets is that you can check if an item exists in constant time (O(1)).

To check if an item is in a set, use the in operator.

Thank you!