Start learning free

LESSON 357 OF 673 · HASH TABLE

Hash Sets in Python

Lesson

Hash Sets are collections of unique items i.e no element can be repeated.

Hash Sets were designed to give us a way of adding and looking for unique values in a collection in a quick manner.

The values in a Hash Set can be either simple primitives like strings or integers as well as more complex object types like object literals or arrays.

In Python, the Hash Set is implemented as the set object.


Creation:

You can create a new empty set by using set():

emptySet = set()

Creating an empty set takes O(1) time.


Constructing from iterable:

The set constructor also accepts an optional iterable object. If you pass an iterable object to the set constructor, all the unique elements from the object will be added to the new set:

elements = [1, '2', 'apple', 1]
mySet = set(elements)

print(mySet) # {1, '2', 'apple'}

This takes O(n) time, where n is the number of elements in the iterable object.


Initialization

Sets containing values can also be initialized by using curly braces:

dataEngineer = {'Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'}

Keep in mind that curly braces can only be used to initialize a set containing values. Empty curly braces ({}) create an empty dictionary, not a set.


Adding elements:

To add an element to the set, you use the add() method:

mySet = {'a', 'b', 'c'}

# Adding new element:
mySet.add('d')

# Adding existing element:
mySet.add('a') # nothing happens

print(mySet) # {'a', 'b', 'c', 'd'}

The set first checks if that element already exists and if so, it does nothing and also doesn't raise an error.

Adding an element to a set takes O(1) time.


Checking if a value exists:

To check if a set has a specific element, you use the in operator:

mySet = {'a', 'b', 'c'}

print('a' in mySet) # True

exist = 'z' in mySet
print(exist) # False

Checking if a value exists in a set takes O(1) time.


Removing elements:

To delete a specified element from a set, you use the remove() method:

mySet = {'a', 'b', 'c', 'd'}

# Deleting elements:
mySet.remove('a')

# Deleting a non-existent element:
mySet.remove('z') # raises KeyError exception

print(mySet) # {'b', 'c', 'd'}

The set first checks if that key exists and if not, it raises a KeyError. If you want a function that leaves a set unchanged if the element is not present, you can use discard():

mySet = {'a', 'b', 'c', 'd'}

# Discarding existent element:
mySet.discard('a') # removes 'a'

# Discarding non-existent element:
mySet.discard('z') # nothing happens

print(mySet) # {'b', 'c', 'd'}

Removing an element from a set takes O(1) time.


Iterating over the Set values:

If we want to iterate over values of the set, we can use the for loop along with the in operator:

mySet = {'b', 'c', 'c', 'd'}

for val in mySet:
    print(val)

# This will print the following:
# b
# d
# c

Notice the order is not the same as we initiated. set keeps the data in random order

Iterating over a set takes O(n) time.


Space Complexity

A set uses O(n) space, where n is the number of elements existing in the set.


Assignment
Follow the Coding Tutorial and let's play with some Hash Sets.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check