Tuples and Sets
Immutable sequences and unique unordered collections
Beyond Lists and Dictionaries
You already know lists and dicts. Now meet their cousins: tuples and sets. Each has a specific purpose that makes your code better.
Tuples — Immutable Sequences
A tuple is like a list that can't be changed after creation. Use parentheses ():
Tuple Basics
Why Use Tuples?
- Safety: Data that shouldn't change (coordinates, RGB values, database rows)
- Performance: Tuples are slightly faster and use less memory than lists
- Dictionary keys: Tuples can be dict keys (lists cannot!)
- Multiple return values: Functions use tuples behind the scenes
Tuple Use Cases
Check Your Understanding
Why can tuples be used as dictionary keys but lists cannot?
Sets — Unique Unordered Collections
A set is an unordered collection of unique elements. Use curly braces {} or set():
Set Basics
Set Operations — The Real Power
Sets support mathematical set operations:
Set Operations
Check Your Understanding
What does {1, 2, 3} & {2, 3, 4} return?
Exercise
Write a function `find_common_words(text1, text2)` that takes two strings, splits them into words, and returns the set of words that appear in BOTH texts (case-insensitive). Also write a function `word_frequency(text)` that returns a list of (word, count) tuples sorted by count (highest first).
Choosing the Right Data Structure
| Type | Ordered? | Mutable? | Duplicates? | Best For |
|---|---|---|---|---|
list | Yes | Yes | Yes | Ordered sequences, stacks |
tuple | Yes | No | Yes | Immutable records, keys |
set | No | Yes | No | Unique items, fast lookup |
dict | Yes* | Yes | Keys: No | Key-value mappings |
(*Dictionaries preserve insertion order since Python 3.7+)
Key Takeaways
- Tuples are immutable lists — perfect for data that shouldn't change
- Tuple unpacking (
a, b = (1, 2)) is one of Python's most elegant features - Sets store unique items and support fast membership testing
- Set operations (
|,&,-,^) are powerful for comparing collections - Choose the right data structure for your use case — it makes your code cleaner and faster