Skip to content

Sets

A set is a data structure that represents a collection of unique elements. Sets are useful when a simpler structure than dictionaries are required.

Definition

example_set = {1, 2, 3 ,4}
print(example_set)
{1, 2, 3, 4}

example_set_two = set() # Sets cannot be defined as {} as they will appear empty.
{1}

Usage

example_set_two.add(1) # Add element to a set
result = 1 in example_set_two # Fast look-up
print(result)
True

example_set_three = set([1, 2, 2, 3, 4]) # Can take a list as an argument and generate a list, note the duplicates
print(example_set_three)
{1, 2, 3, 4}