1 min read

Python Sets

Sets are used to store multiple items in a single variable. A set is a collection which is unordered, unchangeable*, and unindexed.

Note: Set items are unchangeable, but you can remove items and add new items.

Creating a Set

Sets are written with curly brackets.

thisset = {"apple", "banana", "cherry"}
print(thisset)

Access Items

You cannot access items in a set by referring to an index or a key. However, you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

print("banana" in thisset) # Output: True

Add Items

To add one item to a set use the add() method.

thisset.add("orange")

To add items from another set into the current set, use the update() method.

tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)

Remove Items

To remove an item in a set, use the remove(), or the discard() method.

thisset.remove("banana")
thisset.discard("banana")

Set Operations

Union

The union() method returns a new set with all items from both sets.

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

programming/python/python