Tuples & Sets — Python

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…

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'>
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

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

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 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

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.

What you will learn