Today coffee with milk was ordered three times, sweet tea once, toast once. How many different items sold? Three. But to get that number from the list of orders, you would have to count while crossing out the items that repeat. Then there is the receipt already printed for the customer. In the cashier program, another line of code must not change that receipt's data without you noticing.
For data that must not change, and for values that must not repeat, Python has two more containers besides the list. A tuple is an ordered row that is locked: once made, its contents cannot change. A set is a collection of unique values (each value is there only once) with no order. A tuple is like a printed receipt: its order is fixed, and nothing on it can be crossed out. A set is like the "sold" stamps on the menu board: each item that sold gets one stamp. Coffee with milk was ordered three times, but it has only one stamp. The stamps have no position numbers either.
Tuples: a locked row
In this code, the item name and its price on the receipt are stored as one tuple:
receipt = ("coffee with milk", 15)
print(receipt) # ('coffee with milk', 15)
print(receipt[0]) # coffee with milk
print(len(receipt)) # 2
print(type(receipt)) # <class 'tuple'>
- A tuple is written in round brackets
( ), its items separated by commas. - You read it the same way as a list: indexes from 0, negative indexes, slicing,
len()andin. - The difference: a tuple is immutable. It cannot change after it is made. If you try to replace an item with
receipt[1] = 12, Python refuses:
Traceback (most recent call last):
File "/home/darto/stall.py", line 2, in <module>
receipt[1] = 12
~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
- A tuple has no methods that change its contents either.
receipt.append("iced tea")fails withAttributeError: 'tuple' object has no attribute 'append'. - Why lock it? For data that must not change without you noticing: the name and price pair on a receipt, the coordinates of the stall, or several values a function returns at once.
Unpacking a tuple
You can move the items of a tuple into several variables in one line:
receipt = ("coffee with milk", 15)
name, price = receipt
print(name) # coffee with milk
print(price) # 15
name, price = receiptputs the first item innameand the second inprice. This is called unpacking.- The number of variables must match the number of items.
name, price, quantity = receiptfails withValueError: not enough values to unpack (expected 3, got 2). - You have used unpacking already. In the dictionary lesson,
for name, price in menu.items():unpacks a(key, value)tuple on every round of the loop. A function that writesreturn cheapest, priciestalso returns one tuple. You then unpack that tuple into two variables. - A one-item tuple needs a comma:
(42,). Without the comma,(42)is only the number 42 in brackets, and its type isint.
Sets: each value only once
This code stores the items that sold in a set, in two ways:
sold = {"coffee with milk", "sweet tea", "coffee with milk"}
print(len(sold)) # 2
orders = ["coffee with milk", "sweet tea", "coffee with milk", "toast", "coffee with milk"]
distinct_items = set(orders)
print(len(orders), len(distinct_items)) # 5 3
print("sweet tea" in distinct_items) # True
- A set is written in curly braces
{ }, like a dictionary but with no colons. You can also make a set from a list withset(...). - The same value is stored only once. The second
coffee with milkis dropped, solen(sold)is 2. set(orders)is the quick way to drop duplicates (values that appear more than once): 5 orders, but only 3 different items.inchecks whether a value is in the set, the same as with a list..add(x)adds one value..remove(x)removes one value, and raisesKeyErrorwhenxis not in the set.
A set has no order. When the values are text, the printed order can even differ every time the program runs:
$ python3 stall.py
{'coffee with milk', 'sweet tea'}
$ python3 stall.py
{'sweet tea', 'coffee with milk'}
With no order, there are no indexes either. sold[0] is refused with TypeError: 'set' object is not subscriptable (meaning: you cannot read a set's values by index). Need a fixed order? sorted(sold) makes a sorted list.
Set operations
Mr. Darto writes down the numbers of the tables that ordered coffee and of the tables that ordered toast, each group in one set:
coffee_tables = {1, 2, 3, 4}
toast_tables = {3, 4, 5, 6}
print(coffee_tables & toast_tables) # {3, 4}
print(coffee_tables | toast_tables) # {1, 2, 3, 4, 5, 6}
print(coffee_tables - toast_tables) # {1, 2}
In this table, a is coffee_tables and b is toast_tables:
| Operator | Name | What it means at the stall |
|---|---|---|
a & b |
intersection | tables that ordered coffee and toast |
a | b |
union | tables that ordered coffee or toast |
a - b |
difference | tables that ordered coffee but not toast |
Each operator always gives a new set. For example, {1, 2, 3, 4} & {3, 4, 5, 6} is {3, 4}: the values found in both sets.
Which one to use
Choose a container by the properties you need:
| Container | Written | Order and indexes | Can change | Duplicate values |
|---|---|---|---|---|
| list | [ ] |
yes | yes | allowed |
| tuple | ( ) |
yes | no | allowed |
| set | { } or set() |
none | yes, through .add and .remove |
dropped |
| dict | {key: value} |
insertion order, looked up by key | yes | no duplicate keys |
A tuple and a list have one main difference: a tuple is immutable, a list is mutable (it can change).
⚠️ Commas, curly braces and an order you can't rely on
- A one-item tuple without a comma.
x = (42)is anint, not a tuple. Write(42,). - Thinking an empty
{}is a set.{}is an empty dictionary. An empty set is writtenset(). - Relying on a set's order. The printed order can change, and
sold[0]raisesTypeError: 'set' object is not subscriptable. Usesorted(sold)when you need an order. - Unpacking into the wrong number of variables.
name, price = ("coffee with milk", 15, 2)fails withValueError: too many values to unpack (expected 2).
TL;DR: A tuple ( ) is ordered like a list but immutable (it cannot change). That is the main difference between a tuple and a list. Replacing an item, for example receipt[1] = 12, raises TypeError: 'tuple' object does not support item assignment. Unpacking name, price = receipt puts a tuple's items into several variables. A one-item tuple is written with a comma: (42,). A set { } holds unique values with no order and no indexes. Repeated values are dropped, and the printed order can differ every time the program runs. An empty set is written set(), because {} is an empty dictionary. Set operations on two sets: & intersection (the values in both), | union (all values from both), - difference (the values of the left set that are not in the right set). For example, {1, 2, 3, 4} & {3, 4, 5, 6} is {3, 4}.
⚡ A locked row
Write:
receipt = ("coffee with milk", 15)
print(receipt[0]) # coffee with milk
print(len(receipt)) # 2
Guess first: does receipt[1] = 12 work?
No: TypeError: 'tuple' object does not support item assignment. A row of values written in ( ) is a tuple, and a tuple's items can't be replaced.
Meaning: A tuple is written with ( ) and read by index like a list. The difference: a tuple is immutable (it cannot change), a list is mutable (it can change). That's the main difference between them.
⚡ Unpacking a tuple
Write:
receipt = ("coffee with milk", 15)
name, price = receipt
print(name) # coffee with milk
print(price) # 15
Meaning: name, price = receipt is called unpacking: the first item goes to name, the second to price. The number of variables has to match the number of items.
⚡ Sets: each value only once
Guess first: how many values does {"coffee with milk", "sweet tea", "coffee with milk"} hold?
Two. This is a set, and a set keeps each value only once, so the second coffee with milk is dropped.
Meaning: A set { } holds unique values with no order, so there are no indexes. set(orders) makes a set from a list: a quick way to drop repeated values. An empty set is written set(), because {} is an empty dictionary.
⚡ Intersection, union, difference
Write:
coffee_tables = {1, 2, 3, 4}
toast_tables = {3, 4, 5, 6}
print(coffee_tables & toast_tables) # {3, 4}
print(coffee_tables | toast_tables) # {1, 2, 3, 4, 5, 6}
print(coffee_tables - toast_tables) # {1, 2}
Meaning: & (intersection) gives the tables that ordered coffee and toast, | (union) those that ordered coffee or toast, - (difference) those that ordered coffee but not toast.