Python · Module 3 · Lesson 31 min read

Tuples & Sets

Tuples: ordered and unchangeable

point = (3, 4)

  • Use tuples for fixed groups of values: coordinates, RGB colours, database rows.
  • They can be dictionary keys (lists can't).
  • Unpacking: x, y = point, and first, *rest = (1, 2, 3).
  • A one-item tuple needs a comma: (5,). (5) is just the number 5.

Sets: unique values, no order

tags = {"python", "sql"}

  • Duplicates are removed automatically, so set([1, 1, 2]) → {1, 2}.
  • Checking x in my_set is very fast, much faster than in a list for big data.
  • An empty set is set(), because {} is an empty dict.

Set operations

OperatorMeaning
a | bunion (in either)
a & bintersection (in both)
a - bdifference (in a, not b)
a ^ bin one but not both

💡 list(dict.fromkeys(items)) removes duplicates and keeps the order.

▶️ Runs in the app.

Example

Python
point = (3, 4)
x, y = point
print(x, y)                  # 3 4

first, *rest = (1, 2, 3, 4)
print(first, rest)           # 1 [2, 3, 4]

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

emails = ["a@x.com", "b@x.com", "a@x.com"]
print(len(set(emails)))                 # 2 unique
print(list(dict.fromkeys(emails)))      # ['a@x.com', 'b@x.com']