🌱BeginnerData Structures

Tuples and Sets

Immutable ordered tuples and unordered unique-value sets when and why to use each.

Overview

Python has two more built-in collection types you will use regularly: tuples and sets. **Tuples** are ordered, immutable sequences. They look like lists but use parentheses: (1, 2, 3). Because tuples cannot be changed after creation, they are safer for data that should stay fixed (coordinates, RGB values, database records). Tuples are also hashable (when all their elements are hashable), so they can be used as dictionary keys. Functions that return multiple values return them as a tuple. **Sets** are unordered collections of unique values. They automatically eliminate duplicates and excel at membership testing (extremely fast) and set operations: union (|), intersection (&), difference (-), and symmetric difference (^). Sets are mutable you can add and remove items but they are not indexed, so you cannot access elements by position.

Key Points

  • •Tuples use (): `(1, 2, 3)` or just `1, 2, 3` (parentheses optional in many contexts)
  • •A one-element tuple needs a trailing comma: `(42,)` without it `(42)` is just 42
  • •Tuples are immutable attempting to assign to an index raises TypeError
  • •Sets use {}: `{1, 2, 3}` or `set()` for an empty set (not {} which makes a dict)
  • •Sets have no duplicate values and no guaranteed order
  • •Set operations: union `a | b`, intersection `a & b`, difference `a - b`, `in` check is O(1)

Examples

Tuples immutable ordered sequences

point = (3, 7)       # a 2D coordinate
r, g, b = (255, 128, 0)  # tuple unpacking
print(r, g, b)   # 255 128 0

# Tuples can be used as dict keys (lists cannot)
grid = {}
grid[(0, 0)] = "start"
grid[(3, 7)] = "end"
print(grid[(0, 0)])  # start

# One-element tuple note trailing comma!
single = (42,)
print(type(single))  # <class 'tuple'>

Sets unique values, fast membership testing

# Creating sets
colours = {"red", "green", "blue", "red"}  # duplicate "red" dropped
print(colours)       # {'red', 'green', 'blue'} (order may vary)
print(len(colours))  # 3

# Membership test O(1), much faster than list
print("green" in colours)   # True
print("purple" in colours)  # False

# Remove duplicates from a list
nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums))
print(sorted(unique))  # [1, 2, 3, 4]

Set operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # {1, 2, 3, 4, 5, 6} union
print(a & b)   # {3, 4} intersection
print(a - b)   # {1, 2} difference (in a but not b)
print(a ^ b)   # {1, 2, 5, 6} symmetric difference

Common Mistakes

  • Creating an empty set with {} that creates an empty dict! Use set() for an empty set
  • Forgetting the trailing comma in a one-element tuple: (5) is an int, (5,) is a tuple
  • Trying to index a set: sets have no order, so `my_set[0]` raises TypeError

Note

Use sets when you need to check if values exist in a large collection `x in my_set` is O(1) while `x in my_list` is O(n). If you find yourself using a list just to track "seen" values, a set is almost certainly the better choice.

Exercises

Write Python code to solve each exercise. Run it in your browser and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What is the difference between a tuple and a list in Python?