Sets¶
A set in Python is an unordered collection of objects used in situations where
membership and uniqueness to the set are the most important information of the
object. The in
operator runs faster with sets than with Lists:
1 >>> x = set([1, 2, 3, 2, 4])
2 >>> x
3 {1, 2, 3, 4}
4 >>> 1 in x
5 True
6 >>> 5 in x
7 False
- Line 1
You can create a set by applying
set
to a sequence like a list.- Line 3
When a sequence is made into a set, duplicates are removed.
- Line 4 and 6
The keyword is used to check whether an object belongs to a set.
Sets behave like collections of Dictionary keys without associated values.
However, the speed advantage also comes at a price: sets do not keep the elements elements in the correct order, whereas Lists and Tuples do. If the order is important to you, you should use a data structure that remembers the order.
Summary¶
data type |
mutable |
ordered |
indexed |
duplicates |
---|---|---|---|---|
set |
✅ |
❌ |
❌ |
❌ |