Theory

Sets store unique items only (no duplicates).

Create a set:

fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 2, 1} # becomes {1, 2, 3}

Add items:

fruits.add("grape")

Remove items:

fruits.remove("banana")

Check if item exists:

if "apple" in fruits:
print("Has apple!")

Set operations:

a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # Union: {1, 2, 3, 4}
print(a & b) # Intersection: {2, 3}

Exercises in this lesson

2

Remove Duplicates

Given list with duplicates: numbers = [1, 2, 2, 3, 3, 3, 4] Convert it to a set to remove duplicates. Print the length of the set.

Easy Points: 15
3

Set Operations

Given two sets: set_a = {1, 2, 3, 4} set_b = {3, 4, 5, 6} Find and print: 1. Common elements (intersection) using & 2. All elements combined (union) using |

Medium Points: 20
Solve in the playground
Next lesson: String Methods →