Tuples and Sets in Python, and When to Use Each
Use tuples for fixed groups of related values and sets for unique, unordered items. A tuple is a fixed group of values that belong together. A set is a bag of unique items with no order. Every example below was run in Python 3 and shows its real output.
On this page▾
Tuples: values that belong together
The official tutorial describes a tuple as a number of values separated by commas, usually written inside parentheses. You read items by index, just like a list:
office = ("Lisbon", 38.72, -9.14)
print(office[0])
print(len(office))
office[0] = "Porto"
Lisbon
3
TypeError: 'tuple' object does not support item assignment
The last line fails because tuples are immutable: once created, their items cannot be replaced. The tutorial explains the typical difference in use. Lists are mutable and usually hold many items of the same kind, like a list of scores. Tuples usually hold a fixed set of different kinds of values, like a city name and its coordinates, and are often read by unpacking.
The one-item tuple trap
The tutorial calls this one of the syntax quirks of tuples: a tuple with a single item needs a trailing comma, because parentheses alone are not enough.
not_a_tuple = ("Lisbon")
a_tuple = ("Lisbon",)
print(type(not_a_tuple))
print(type(a_tuple))
<class 'str'>
<class 'tuple'>
It is the comma that makes a tuple, not the parentheses. An empty tuple is written as ().
Unpacking tuple values
You can pull every item of a tuple into its own variable in one line. The tutorial calls this sequence unpacking, and notes that the number of variables on the left must match the number of items.
city, lat, lon = ("Lisbon", 38.72, -9.14)
print(city, lat, lon)
first, last = "Ada", "Lovelace"
first, last = last, first
print(first, last)
Lisbon 38.72 -9.14
Lovelace Ada
The swap on the last line of that block works because the right side builds a tuple first, then unpacks it into the two names. The tutorial describes multiple assignment as exactly this combination of packing and unpacking.
Functions use the same trick to return more than one value:
def min_max(numbers):
return min(numbers), max(numbers)
result = min_max([7, 2, 9, 4])
print(result)
low, high = min_max([7, 2, 9, 4])
print(low, high)
(2, 9)
2 9
The function returns one tuple, and the caller can keep it whole or unpack it.
Tuples as dictionary keys
Tuples can be dictionary keys only when all their elements are hashable. Immutability alone is not enough: a tuple containing a list, directly or inside another tuple, cannot be a key. That is handy for anything identified by two parts, like a floor and a desk letter:
desks = {(1, "A"): "Mina", (1, "B"): "Leo", (2, "A"): "Sam"}
print(desks[(1, "B")])
Leo
How dictionaries work is covered in Python Dictionaries Explained With Simple Examples.
Sets: unique items, fast membership checks
The tutorial defines a set as an unordered collection with no duplicate elements, and names its basic uses: membership testing and eliminating duplicate entries. Passing a list to set() removes repeats:
signups = ["mina", "leo", "sam", "leo", "ana", "mina"]
unique = set(signups)
print(len(signups), len(unique))
print(sorted(unique))
print("ana" in unique)
6 4
['ana', 'leo', 'mina', 'sam']
True
Six sign-ups came from four people. Because sets have no order, the tutorial warns that printing one may show items in an unexpected order, which is why sorted() is used here to get a predictable list.
That missing order also means sets have no positions:
tags = {"urgent", "billing"}
print(tags[0])
TypeError: 'set' object is not subscriptable
Set math: compare two groups in one line
Sets support the operations from math class. Here are attendees of two meetings:
monday = {"mina", "leo", "sam", "ana"}
friday = {"leo", "ana", "raj"}
print(sorted(monday & friday))
print(sorted(monday | friday))
print(sorted(monday - friday))
print(sorted(monday ^ friday))
['ana', 'leo']
['ana', 'leo', 'mina', 'raj', 'sam']
['mina', 'sam']
['mina', 'raj', 'sam']
&(intersection): in both meetings.|(union): in either meeting.-(difference): came Monday but not Friday.^(symmetric difference): came to exactly one meeting.
With sets, each of these comparisons is one operator, without an explicit loop.
The empty set gotcha
The tutorial points out that {} creates an empty dictionary, not an empty set. Use set():
empty = {}
print(type(empty))
empty_set = set()
print(type(empty_set))
empty_set.add("mina")
empty_set.add("mina")
print(empty_set)
<class 'dict'>
<class 'set'>
{'mina'}
Adding the same name twice still leaves one copy.
Which one should you use?
| You need | Use |
|---|---|
| An ordered collection you will change | list |
| A fixed group of related values, or a dictionary key | tuple |
| Unique items, or a quick "is it in here?" check | set |
| To compare two groups | set operators |
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published