Python16 min read

Python Sets

Learn sets for unique values, membership checks, and set operations like union and intersection with clear examples.

Emily Davis
September 9, 2025
8.0k202

A set is an unordered collection of unique values.

Use sets when:
- you need to remove duplicates
- you want fast membership checks: `x in set`
- you want to compare groups (common items, missing items)

## Create a set (duplicates auto removed)

```python
unique_numbers = {1, 2, 2, 3, 3, 3}
print(unique_numbers)
```

Expected output:

```
{1, 2, 3}
```

## Add and remove

```python
fruits = {"apple", "banana"}

fruits.add("orange")
print(fruits)

fruits.remove("banana")
print(fruits)

fruits.discard("grape")  # safe remove
print(fruits)
```

Expected output (order may vary):

```
{'orange', 'apple', 'banana'}
{'orange', 'apple'}
{'orange', 'apple'}
```

## Set operations (powerful part)

```python
east = {"New York", "Boston", "Miami"}
west = {"Los Angeles", "Seattle", "Denver"}
south = {"Miami", "Houston", "Austin"}

print(east | west)    # union
print(east & south)   # intersection
print(east - south)   # difference
```

Expected output (order may vary):

```
{'New York', 'Boston', 'Miami', 'Los Angeles', 'Seattle', 'Denver'}
{'Miami'}
{'New York', 'Boston'}
```

## Membership checks (fast)

```python
cities = {"Chicago", "Dallas", "Phoenix"}
print("Chicago" in cities)
print("Seattle" not in cities)
```

Expected output:

```
True
True
```

## Graph: how set operations relate

```mermaid
flowchart LR
  A[east] --> B[intersection]
  C[south] --> B
  B --> D[common elements]
  A --> E[union]
  F[west] --> E
  E --> G[all unique]
```

In the next lesson, you will learn input and output so your program can interact with users.
#Python#Beginner#Sets