Loading lessons...
Sets
A set is an unordered collection of unique items. No duplicates, no indexes.
Create a set
python
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
python
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
### {'apple', 'banana', 'cherry'}
Check length
python
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:
python
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.