Chapter 9

Tuples and Sets

Learn how tuples hold fixed ordered data and how sets store unique unordered items.

What is a Tuple?

A tuple is an ordered collection of items, much like a list. The key difference is that a tuple is immutable: once you create it, you cannot change, add, or remove its items. You write tuples with round brackets.

point = (3, 5)
print(point[0])   # prints 3
print(point[1])   # prints 5

Because tuples cannot change, they are useful for data that should stay fixed, such as coordinates, colours, or a date. Trying to reassign an item raises an error.

point = (3, 5)
point[0] = 9   # TypeError: tuples do not support item assignment

A tricky detail: a tuple with a single item still needs a comma. Writing (5) is just the number 5 in brackets, but (5,) is a one-item tuple.

What is a Set?

A set is an unordered collection of unique items. Any duplicate values are removed automatically. You create sets with curly braces, or with the set() function.

nums = {1, 2, 2, 3}
print(nums)          # {1, 2, 3}
print(len(nums))     # 3

Because sets are unordered, you cannot use an index like nums[0]. Sets are excellent when you want to check membership quickly or strip duplicates from a list.

words = ['a', 'b', 'a', 'c']
unique = set(words)
print(len(unique))   # 3

Set Operations

Sets support handy maths-style operations. Union (the vertical bar) joins two sets, intersection (the ampersand symbol) keeps shared items, and difference (the minus sign) removes items found in the second set.

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

To create an empty set you must write set(), because empty curly braces make an empty dictionary instead.

When to Choose Each One

Reach for a tuple when the group of values should never change, such as a pair of screen coordinates or the days of the week. The immutability acts as a safety net, since accidental edits are caught as errors rather than silently corrupting your data. Reach for a set when you care about membership and uniqueness, for example checking whether a username has already been used or counting how many different words appear in a piece of text. Both types can be created from a list, and both can be looped over with a simple for statement.

Remember

  • Tuples use round brackets and are immutable.
  • A one-item tuple needs a trailing comma, like (5,).
  • Sets hold only unique items and ignore duplicates.
  • Sets are unordered, so they have no index positions.
  • Use set() to make an empty set, not empty curly braces.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor