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.
To create an empty set, use the
set() constructor method:
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.
You cannot create an empty set using curly brackets, Python will assume you are creating a dictionary!
Adding to a setO(1)
Adding to a set is easy, just use the
Removing an item from a setO(1)
You can remove an item from a set with 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, I recommend using
discard() to avoid interruptions caused by exceptions. However, it is important to note that in general, it's best practice to appropriately throw, catch, and handle exceptions.
Checking if an object exists in a setO(1)
Since sets are unordered in Python, you won't typically retrieve a single item from a set. However, 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