Python Sets

Python Sets

A set is a collection which is unordered, unchangeable*, and unindexed. Sets are written with curly brackets {}.

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

Create a Set

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

Duplicates Not Allowed

Sets cannot have two items with the same value. If you try to add a duplicate, it will simply be ignored.

No Duplicates

thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) // The second "apple" is missing!

Add and Remove Items

Once a set is created, you cannot change its items, but you can add new items using add() and remove items using remove() or discard().

Add and Remove

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

// Add an item thisset.add("orange")

// Remove an item thisset.remove("banana")

print(thisset)


Joining Sets

Sets have powerful mathematical built-in methods, such as union() (combines two sets) and intersection() (keeps only items that exist in both sets).


Exercise

?

Which feature makes a Set different from a List or Tuple?