Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Working with Sets
Lists, tuples, and ranges are sequences. Their values have an order and can be accessed by index. A set is different: it stores unique values without an index-based order.
Create a set with braces or with set.
variable = {value1, value2, ...}
variable = set([value1, value2, ...])
Sets are useful for membership checks and set operations.
Set Operations
Adding a Value
set_value.add(value)
Adding an existing value does not change the set.
Removing a Value
set_value.remove(value)
Obtaining the Number of Elements
variable = len(set_value)
Obtaining Maximum and Minimum Values
variable = max(set_value)
variable = min(set_value)
Set Difference
set1 - set2
Returns a new set containing values from set1 that are not in set2.
Comparing Sets
Use ==, !=, <, <=, >, and >= to compare sets. The ordering operators represent subset and superset relationships, not numeric size. For example, A > B checks whether A is a proper superset of B.
Logical Set Operations
set1 & set2
set1 | set2
set1 ^ set2
| Operator | Result |
|---|---|
& |
Intersection: values in both sets |
| |
Union: values in either set |
^ |
Symmetric difference: values in only one set |
a = {'a', 'b'}
b = {'b', 'c'}
c1 = a & b
c2 = a | b
c3 = a ^ b
print(c1)
print(c2)
print(c3)