A set is an unordered collection of **unique** elements. Sets are mutable, but elements must be hashable (immutable types like strings, numbers, tuples). Sets do not support indexing — you cannot access `s[0]`.
## Creating sets
```python
s = {1, 2, 3}
empty = set() # NOT {} — that creates an empty dict!
from_list = set([1, 2, 2, 3, 3])
print(from_list) # {1, 2, 3} — duplicates removed automatically
```
## Adding and removing
```python
s = {1, 2, 3}
s.add(4) # adds 4 to the set
s.add(2) # no effect — 2 already exists
print(s) # {1, 2, 3, 4}
s.remove(3) # removes 3 — raises KeyError if not found
s.discard(99) # removes 99 if present — NO error if not found
print(s) # {1, 2, 4}
popped = s.pop() # removes and returns an ARBITRARY element
print(popped) # some element (sets are unordered)
s.clear() # removes all elements
print(s) # set()
```
## Set operations
```python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union: all elements from both
print(a | b) # {1, 2, 3, 4, 5, 6}
print(a.union(b)) # same
# Intersection: only elements in BOTH
print(a & b) # {3, 4}
print(a.intersection(b)) # same
# Difference: in A but NOT in B
print(a - b) # {1, 2}
print(a.difference(b)) # same
# Symmetric difference: in A or B but NOT both
print(a ^ b) # {1, 2, 5, 6}
print(a.symmetric_difference(b)) # same
```
## Subset and superset checks
```python
small = {1, 2}
big = {1, 2, 3, 4}
print(small.issubset(big)) # True — all of small is in big
print(small <= big) # same using operator
print(big.issuperset(small)) # True — big contains all of small
print(big >= small) # same
print(small.isdisjoint({5, 6})) # True — no elements in common
```
## In-place update methods
```python
a = {1, 2, 3}
a.update({3, 4, 5}) # adds all elements (like |=)
print(a) # {1, 2, 3, 4, 5}
a.intersection_update({2, 3}) # keeps only elements in both
print(a) # {2, 3}
a.difference_update({3}) # removes elements in argument
print(a) # {2}
```
## Deduplication
The most common use case for sets: removing duplicates from a list while keeping one copy of each value.
```python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
unique = list(set(numbers))
print(sorted(unique)) # [1, 2, 3, 4, 5, 6, 9]
```
Note: converting to set loses the original order. To preserve order while removing duplicates, use a different approach:
```python
def deduplicate(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(deduplicate([3, 1, 4, 1, 5, 9, 2, 6, 5]))
# [3, 1, 4, 5, 9, 2, 6]
```
## Finding common and unique elements
```python
team_a = {"Alice", "Bob", "Carol", "David"}
team_b = {"Bob", "David", "Eve", "Frank"}
# Who is on both teams?
both = team_a & team_b
print(both) # {"Bob", "David"}
# Who is only on team A?
only_a = team_a - team_b
print(only_a) # {"Alice", "Carol"}
# Everyone involved (no duplicates)
everyone = team_a | team_b
print(everyone) # {"Alice", "Bob", "Carol", "David", "Eve", "Frank"}
# Who is on exactly one team?
exclusive = team_a ^ team_b
print(exclusive) # {"Alice", "Carol", "Eve", "Frank"}
```
## Checking membership
```python
# Set lookup is O(1) — much faster than list for large collections
allowed_extensions = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
def is_image(filename):
_, ext = filename.rsplit(".", 1) if "." in filename else (filename, "")
return f".{ext.lower()}" in allowed_extensions
print(is_image("photo.jpg")) # True
print(is_image("doc.pdf")) # False
print(is_image("readme.txt")) # False
```
## Set comprehension
```python
words = ["hello", "world", "hello", "python", "world"]
unique_words = {w.lower() for w in words}
print(unique_words) # {"hello", "world", "python"}
# Unique first letters
first_letters = {word[0] for word in ["apple", "banana", "avocado", "cherry"]}
print(sorted(first_letters)) # ["a", "b", "c"]
```
## Mutating methods
| Method | What it does |
|---|---|
| `s.add(x)` | Add `x` to the set |
| `s.remove(x)` | Remove `x` (raises `KeyError` if not found) |
| `s.discard(x)` | Remove `x` if present, no error if absent |
| `s.pop()` | Remove and return an arbitrary element |
| `s.clear()` | Remove all elements |
| `s.update(other)` | Add all elements of `other` to `s` |
| `s.intersection_update(other)` | Keep only elements in both |
| `s.difference_update(other)` | Remove elements found in `other` |
## Set operations — methods and operators
| Operation | Method | Operator | Result |
|---|---|---|---|
| Union | `a.union(b)` | `a | b` | All elements from A and B |
| Intersection | `a.intersection(b)` | `a & b` | Only in both A and B |
| Difference | `a.difference(b)` | `a - b` | In A, not in B |
| Symmetric diff | `a.symmetric_difference(b)` | `a ^ b` | In A or B, not both |
| Subset | `a.issubset(b)` | `a <= b` | All of A is in B |
| Superset | `a.issuperset(b)` | `a >= b` | A contains all of B |
| Disjoint | `a.isdisjoint(b)` | — | A and B share no elements |
## Operators vs methods
Operators (`|`, `&`, `-`, `^`) require **both operands to be sets**.
Methods (`.union()`, `.intersection()`, etc.) accept **any iterable** as argument:
```python
s = {1, 2, 3}
s.union([3, 4, 5]) # OK — list accepted
s | [3, 4, 5] # TypeError — operator needs a set
```
## Set comprehension
```python
{expr for var in iterable}
{expr for var in iterable if condition}
```
## Common patterns
```python
# Deduplicate preserving order
seen = set()
result = [x for x in lst if not (x in seen or seen.add(x))]
# Fast membership test
VALID = {"admin", "editor", "viewer"}
if role not in VALID:
raise ValueError(f"Unknown role: {role}")
# Find common elements in multiple sets
common = set.intersection(*list_of_sets)
```
Write a function `safe_remove(s, value)` that removes `value` from set `s` if it exists, and returns `True` if it was removed or `False` if it was not found. The function must never raise an error. Example: `s = {1, 2, 3}; safe_remove(s, 2)` → `True`, `s == {1, 3}`; `safe_remove(s, 99)` → `False`.
def safe_remove(s, value):
pass
s = {1, 2, 3}
print(safe_remove(s, 2)) # True (s is now {1, 3})
print(safe_remove(s, 99)) # False
Solution
def safe_remove(s, value):
if value in s:
s.discard(value)
return True
return False
# Or even simpler:
def safe_remove_v2(s, value):
before = len(s)
s.discard(value)
return len(s) < before
s = {1, 2, 3}
print(safe_remove(s, 2)) # True
print(safe_remove(s, 99)) # False
Write a function `unique_ordered(lst)` that removes duplicate elements from a list while preserving the order of first appearances. Example: `unique_ordered([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])` → `[3, 1, 4, 5, 9, 2, 6]`. Use a set to track seen elements.
def unique_ordered(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(unique_ordered([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
# [3, 1, 4, 5, 9, 2, 6]
Write a function `common(a, b)` that returns a set of elements that appear in both lists `a` and `b`. Example: `common([1, 2, 3, 4], [3, 4, 5, 6])` → `{3, 4}`. Convert to sets and use an intersection operation.
Write a function `exclusive(a, b)` that returns a set of elements that appear in exactly one of the two lists (but not both). Example: `exclusive([1, 2, 3], [2, 3, 4])` → `{1, 4}`. Use the symmetric difference operation.
Write a function `is_subset(small, big)` that returns `True` if every element of `small` is also in `big`. Both arguments can be lists or sets. Example: `is_subset([1, 2], [1, 2, 3, 4])` → `True`, `is_subset([1, 5], [1, 2, 3])` → `False`.
Write a function `unique_word_count(text)` that returns the number of unique words in a text string (case-insensitive). Example: `unique_word_count("The cat sat on the mat the cat")` → `5` (the, cat, sat, on, mat).
def unique_word_count(text):
pass
print(unique_word_count("The cat sat on the mat the cat"))
# 5 (the, cat, sat, on, mat)
Solution
def unique_word_count(text):
return len(set(text.lower().split()))
print(unique_word_count("The cat sat on the mat the cat"))
# 5 (the, cat, sat, on, mat)
Write a function `has_only_valid(s, allowed)` that returns `True` if every character in string `s` is contained in the string `allowed`. Example: `has_only_valid("hello", "aehllo")` → `True`, `has_only_valid("hello!", "aehllo")` → `False`. Use set operations.
Write a function `vowel_set(text)` that returns a set of all unique vowels (a, e, i, o, u) that appear in `text` (case-insensitive). Use a set comprehension. Example: `vowel_set("Hello World")` → `{"e", "o"}`.
Students can join Club A, Club B, or both. Given two sets `club_a` and `club_b` of student names, write a function `venn(club_a, club_b)` that returns a dict with three keys: `"only_a"` (in A only), `"only_b"` (in B only), `"both"` (in both). Example: `venn({"Alice", "Bob", "Carol"}, {"Bob", "Carol", "David"})` → `{"only_a": {"Alice"}, "only_b": {"David"}, "both": {"Bob", "Carol"}}`.
Write a function `common_all(*lists)` that returns a set of elements that appear in ALL of the given lists. Example: `common_all([1, 2, 3], [2, 3, 4], [2, 3, 5])` → `{2, 3}`. Handle the case where no lists are given (return empty set).
def common_all(*lists):
if not lists:
return set()
result = set(lists[0])
for lst in lists[1:]:
result &= set(lst)
return result
print(common_all([1, 2, 3], [2, 3, 4], [2, 3, 5])) # {2, 3}
print(common_all([1, 2], [3, 4])) # set()
print(common_all()) # set()
No split tab
Cookie preferences
We use necessary cookies to run the site. With your permission, we can also save your site preferences and use analytics and advertising cookies to understand usage and support the project.
Open tools in tabs.Exercises, IDE tools, and trainers stay available as site tabs.
Switch without losing context.Move between explanations, code, and utilities while keeping your place.
Use the sidebar as your map.The left panels hold navigation, settings, files, libraries, and tool controls.
PythonJavaScriptSQLite
One IDE, three practical modes
Python in the browser.Run small scripts, try libraries, and practice API requests without installing anything.
JavaScript for quick experiments.Test browser-friendly code and compare ideas next to your learning materials.
SQLite for data practice.Open the database explorer to inspect tables, write queries, and learn SQL workflows locally.
TopicIDE
Work side by side with split tabs
Keep instructions visible.Open an exercise or reference page beside the IDE instead of jumping back and forth.
Compare tools while you learn.Place regex checks, explanations, and code experiments next to each other when the task needs it.
Close the split when you are done.The workspace returns to a single focused tab, and your open site tabs remain available.
Code Typing Trainer
Or plain text
This trainer is designed for a physical keyboard.Open this section on a laptop or desktop with a wide screen. Touch typing practice will not work correctly on a phone.
Speed: 0 chars/min
0 words/min
Best speed (60s): 0 chars/min
0 words/min
Errors: 0
Total time: 0.0 s
To practice touch typing, avoid looking at your physical keyboard.