Python5 min read

Python Sets

Store unique items using sets in Python.

Emily Davis
December 18, 2025
0.0k0

Work with unique values.

Create Set

```python cities = {"Miami", "Austin", "Denver"} numbers = {1, 2, 3, 4, 5}

Duplicates are removed automatically unique = {1, 2, 2, 3, 3, 3} print(unique) # {1, 2, 3} ```

Add and Remove

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

Add item fruits.add("orange")

Remove item fruits.remove("banana") # or fruits.discard("grape") # Won't error if not found

print(fruits) ```

Set Operations

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

Union (combine) all_cities = east | west print(all_cities)

Intersection (common) common = east & south print(common) # {'Miami'}

Difference only_east = east - south print(only_east) # {'New York', 'Boston'} ```

Check Membership

```python cities = {"Chicago", "Dallas", "Phoenix"}

print("Chicago" in cities) # True print("Seattle" not in cities) # True ```

Remember

- Sets have no duplicates - Sets are unordered - Use for unique values

#Python#Beginner#Sets