We're making some improvements. Some features may be temporarily unavailable.
intermediate15 min

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

Output
Run your code to see output here

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

Output
Run your code to see output here

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

Output
Run your code to see output here

Set Operations — The Real Power

Sets support mathematical set operations:

Set Operations

Output
Run your code to see output here

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).

Python will load on first run

Choosing the Right Data Structure

TypeOrdered?Mutable?Duplicates?Best For
listYesYesYesOrdered sequences, stacks
tupleYesNoYesImmutable records, keys
setNoYesNoUnique items, fast lookup
dictYes*YesKeys: NoKey-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

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...