Loading lessons...
Sets
Sets
A set is an unordered collection of unique items. No duplicates, no indexes.
Create a set
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set properties
- Unordered: items have no defined order; you can't index them.
- Unchangeable: you can't change an item, but you can add/remove items.
- No duplicates: the same value appears only once.
- Unindexed:
thisset[0]raises a TypeError.
Duplicates are dropped
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) # {'apple', 'banana', 'cherry'}
Check length
print(len(thisset)) # 3
Set items can be any type
But they must be hashable, so no lists or dicts inside a set.
Membership test
in is the fastest way to check a set:
print("banana" in thisset) # True
A note on order
Since sets are unordered, printing one may show items in any order.
TL;DR
- Sets use
{ }with no key-value pairs. - Unordered, unindexed, no duplicates.
- Items must be hashable (no lists/dicts).
inchecks membership quickly.