Python sets
// updated 2025-11-06 18:58
We have so far looked at a few collection data types in Python:
- lists (with ordered and changeable elements)
- tuples (with ordered but unchangeable elements)
- dictionaries (with unordered but changeable elements)
To finish this off, we have sets (with unordered and unchangeable elements)!
Creating a set
In Python, we denote sets with a pair of curly braces:
my_set = { "Jon", 100, True }Accessing items in a set
We cannot access items in a set via indices or keys, but we can see if they exist in the set using the in keyword:
my_set = { "Jon", 100, True }
print("Jon" in my_set)
# TrueAdding set items
Note that while we can add items to the set, we can change any items once they exist in the set with the add(argument) method and by passing the new item as the argument:
my_set = { "Jon", 100, True }
# we can add items to the set but cannot change any existing items
my_set.add("Pass")
# printing the set can print the items in any order
print(my_set)
# { True, "Jon", 100, "Pass"}
Updating a set (but not its items)
Now, we can also update a set (i.e. add multiple items at once), but not its individual items, by using the update(argument) built-in method and by passing another set as the argument:
my_set = { 'apples', 'bananas', 'oranges' }
# we can update the set (i.e. add multiple items to the set) but cannot change any existing items
my_set.update({'grapes', 'coconuts', 'watermelons', 'apples'})
# any duplicates get removed
print(my_set)
# {'oranges', 'grapes', 'bananas', 'coconuts', 'apples', 'watermelons'}Note that any duplicates get removed when passing it in the argument set!
Removing items from a set
Note that if we know the exact value of an item in a set, we can use the remove(argument) built-in function and pass in our desired value as the argument:
fruits = { 'apples', 'bananas', 'oranges', 'grapes', 'watermelons', 'coconuts' }
fruits.remove('apples')
print(fruits)
# {'coconuts', 'bananas', 'oranges', 'grapes', 'watermelons'}Summary
We can think of a set as:
- an unordered collection of one or more immutable (unchangeable) items:
- indexed neither by keys nor values
- we can still "look up" items via the
inkeyword
- we can still "look up" items via the
- not capable of update
- indexed neither by keys nor values
- capable of adding and removing items via built-in methods
- denoted by curly braces containing items
{ value1, ..., valueN }
Applications
Great uses for sets include collections of:
- objects whose names should not change and their order doesn't matter, e.g.:
- names for use in a raffle draw
- numbers for a lottery draw