…
…
Python Programming Fundamentals · Lesson 29 / 40 · Tuples and sets
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada wants two things: to get the day's revenue and the number of orders in one go, and to compare the customer book of two days (how many different people came, and who stopped by on both days?). In this lesson you will meet the new structures that do these two jobs, and you will learn to decide which structure is right for a piece of data.
The program you will write at the end of the lesson will print this:
OutputRevenue: $18.00, 4 orders
Different customers: 3
Came on both days: ['Alex', 'Maya']So far you have used two structures: the list, which keeps items in order and which you can change whenever you like, and the dictionary, which you reach by name. Ada's requests do not fit them well. A function needs to give back the revenue and the order count together, but a function returns only one thing with return. In the customer book, if Ada comes twice she appears twice in the list; to answer "how many different people?" you need to drop the repeats. The two new structures in this lesson, the tuple and the set, exist for exactly these jobs.
In this lesson you will:
Think of a product on the menu: its name is "latte", its price is 4.25. These two values mean something together; without one, the other is incomplete. You could put them in a list, but a list says "you can change this later." If a line of code accidentally writes product[1] = 0, the latte is sold for free and nobody notices. A tuple is a structure that keeps values in order but does not allow them to be changed afterward. It is written with normal parentheses and commas: product = ("latte", 4.25).
Reading a tuple works like reading a list. You reach an element by its index (product[0]), get the number of elements with len, ask whether a value is there with in, and walk through the elements with for. The difference shows up only when you change it: you cannot add an element to a tuple, delete one, or put another value in place of one.
Example 1 (case): Keeping a product in a tuple
product = ("latte", 4.25) print(product[0], product[1], len(product)) name, price = product print(f"{name}: ${price:.2f}")
Outputlatte 4.25 2
latte: $4.25The first print reads the tuple like a list: element 0 is latte, element 1 is 4.25, and there are 2 elements. The third line does something new: it unpacks the tuple. The two elements of the tuple on the right are handed out in order to the two names on the left; the name box gets "latte" and the price box gets 4.25. You will see unpacking in detail in the next section.
But what happens if the price really does change? Predict first.
What happens when this code runs?
product = ("latte", 4.25)
product[1] = 4.50Touch a tuple yourself with the boxes below. Operations that read (looking at an element, counting, searching) work; operations that change (replacing, adding, deleting) raise an error.
Touch the tuple: which operations work, and which raise an error?
Press an operation; predict what Python will say first.
A tuple can't be changed: reading operations work, changing operations raise an error.
No operations yet. Press a button above.
Let's put the list and the tuple side by side:
| List | Tuple | |
|---|---|---|
| Syntax | ["latte", 4.25] | ("latte", 4.25) |
Reading by index, len, in, for | Yes | Yes |
| Adding, deleting, changing elements | Yes | No (raises an error) |
| Can it be a dictionary key? | No | Yes |
| When to use it | When the contents will grow and shrink | When the values belong together and stay fixed |
Not being able to change looks like a restriction, but it does two jobs. First, values that belong together are not broken by accident somewhere else in the code. Second, a tuple can be a dictionary key. If the café sells the latte in two sizes, you want to attach the price to the pair "product and size." A dictionary key must not change; a list cannot be a key (it raises a TypeError whose message contains unhashable type: 'list'), but a tuple can.
Example 2 (case): A tuple as a dictionary key
price_by_size = {("latte", "small"): 3.75, ("latte", "large"): 4.75}
print(price_by_size[("latte", "large")])Output4.75You have actually seen tuples before; we just never gave them a name. When you walk through two lists together with zip, each round gives a tuple. In a dictionary, items() also gives a (key, value) tuple in each round: list({"latte": 4.25, "tea": 1.25}.items()) gives [('latte', 4.25), ('tea', 1.25)]. The right side of a line like latte, cookie = 4.25, 2.00 is also a tuple.
One last detail: what makes a tuple is the comma, not the parentheses. (5) is only a number inside parentheses; its type is int. For a one-element tuple you need the comma: (5,). Writing product = "latte", 4.25 without parentheses also creates a tuple.
Reading the elements of a tuple one by one as product[0], product[1] works, but it is hard to read: what was product[1], the price or the size? Unpacking solves this: when you write name, price = product, the elements of the tuple are handed out to the names on the left in order. There is a single rule: the number of names on the left must equal the number of elements in the tuple. If you try to unpack a three-element tuple into two names, Python raises a ValueError that starts with too many values to unpack; in the opposite case, with more names than elements, it says not enough values to unpack.
Unpacking has two useful results. The first is swapping: to swap the values of two variables, writing a, b = b, a is enough. Python first computes the right side and builds the tuple (value of b, value of a), then unpacks that tuple to the left. You do not need a temporary third variable.
The second is the answer to Ada's first request: a function can return two values. When you write return total, count, the comma again builds a tuple; the function returns one thing, this tuple. The caller unpacks the tuple right away: revenue, order_count = day_summary(day). You can also unpack in a loop: if the list is made of (product, quantity, price) tuples, for product, quantity, price in day: hands each tuple out to three variables in every round.
Example 3 (case): The day's summary from one function
day = [("latte", 2, 4.25), ("tea", 3, 1.25), ("latte", 1, 4.25), ("water", 2, 0.75)] def day_summary(orders): # 1. Accumulate the revenue total = 0 for product, quantity, price in orders: total += quantity * price # 2. Return both values together return total, len(orders) revenue, order_count = day_summary(day) print(f"Revenue: ${revenue:.2f}, {order_count} orders")
OutputRevenue: $18.00, 4 ordersIn the first round of the loop the tuple ("latte", 2, 4.25) is unpacked: product becomes "latte", quantity becomes 2, price becomes 4.25, and 8.50 is added to total. After four rounds the total is 8.50 + 3.75 + 4.25 + 1.50 = 18.00. The return line returns the tuple (18.0, 4), and the line before the last one unpacks it into the revenue and order_count boxes. The first line of the lesson's target output is ready.
Step through the code below. Notice that two boxes fill in the same step on the unpacking lines, and that there is no temporary variable in the swap. Then use "Change the code" to add 6.00 to the price list and step through it again.
Run the code line by line: see which line runs next, the variable boxes and the output.
def min_max(prices): return min(prices), max(prices) product = ("latte", 4.25) name, price = product cheapest, priciest = min_max([4.25, 2.00, 1.25, 0.75]) a, b = 4.25, 2.00 a, b = b, a print(name, price) print(cheapest, priciest) print(a, b)
What happens if you do not unpack the return value? Predict.
min_max is defined as above. What does this code print?
def min_max(prices): return min(prices), max(prices) result = min_max([4.25, 2.00, 1.25, 0.75]) print(result)
Let's move on to Ada's second request. The customers who came on Monday were written in the book in order: ["Ada", "Alex", "Ada", "Maya", "Alex"]. The list has five elements, but three different people came. To drop the repeats by hand you could write a loop and if ... not in ...; a set does this job in one step. A set is a structure that keeps each element only once and does not care about order. It is written with curly braces ({"Ada", "Alex"}) or built from a list: set(items).
A set has three strong sides. It drops repeats, so len(a_set) gives the number of different elements. It answers "is this person here?" quickly with in: a list looks at the elements one by one from the start for this question, a set does not; in a book with thousands of names the difference is big. And it compares two groups; you will see that in the next section.
Example 4 (case): How many different customers?
customers = ["Ada", "Alex", "Ada", "Maya", "Alex"] unique = set(customers) print(len(customers), len(unique)) print("Maya" in unique) print(sorted(unique))
Output5 3
True
['Ada', 'Alex', 'Maya']Why did we print the set with sorted on the last line? A set has no order: it does not keep elements in the order they were added, and the order that print(unique) shows may not be the same on every run. It has no index either; unique[0] raises an error. When you want to see it in order, sorted(a_set) gives you an alphabetical list. In this lesson we will always print sets this way, so the output is the same every time.
What does this code print?
print(len({"tea", "latte", "tea"}))
A set can be changed: you add and remove elements. add adds an element; if the element is already there, nothing happens and there is no error. There are two ways to remove: discard passes silently if the element is missing, and remove raises a KeyError if the element is missing. If you mean "this person must be on the list, and if not, something is wrong," you choose remove; if you mean "remove if present," you choose discard. Try it yourself below.
Touch the set: can the same element be added twice, and what happens when you remove one that is not there?
Press an operation; predict what Python will say first.
A set has no order and no index; the arrangement of the boxes means nothing.
No operations yet. Press a button above.
A set asks "is it the same?" letter by letter. In your eyes "Ada", "ada", and "Ada " with a space at the end are the same person; for the set the three are three different strings. Below, change the name added to the set and watch the element count.
What happens to the element count when the name added to the set changes? Change the value of new.
Pick a value; predict the output first, then look.
1arrived = {"Ada", "Alex", "Maya"}2new = "Noah"3arrived.add(new)4print(len(arrived))5print(sorted(arrived))
4 ['Ada', 'Alex', 'Maya', 'Noah']
Faded lines didn't run with this value. Only the letter-for-letter identical "Ada" does not grow the set. The lowercase "ada" and "Ada " with a trailing space count as new elements. That is why you clean a string before putting it in a set: strip() removes the spaces and lower() lowercases the letters (lesson 21). Also notice that the lowercase "ada" sorts to the end.
Ada's real question is comparing two days. Sets offer three operations for this:
| Operation | Syntax | Result | Meaning in the café | |
|---|---|---|---|---|
| Intersection | a & b | Those in both | Those who came on both days | |
| Union | `a \ | b` | Those in at least one | All different people who came in the two days |
| Difference | a - b | Those in a but not in b | Those who came on Monday but not on Tuesday |
In intersection and union the order does not matter: a & b and b & a give the same result. In difference the order matters, because the question changes. tuesday - monday answers "who are the new people on Tuesday?"; monday - tuesday answers "who came on Monday but not on Tuesday?" Think of it like subtraction with numbers: 5 - 3 and 3 - 5 are not the same.
Example 5 (case): The customers of two days
monday = {"Ada", "Alex", "Maya"}
tuesday = {"Alex", "Maya", "Noah"}
print(sorted(monday & tuesday))
print(sorted(monday | tuesday))
print(sorted(monday - tuesday))
print(sorted(tuesday - monday))Output['Alex', 'Maya']
['Ada', 'Alex', 'Maya', 'Noah']
['Ada']
['Noah']The elements of a set must be of an unchangeable type: numbers, strings, and tuples go into a set, lists do not. The rule for dictionary keys applies here too. That is why, later on, you will keep positions like (row, seat) in a set as tuples.
Below, match each expression to its result using the sets of Example 5.
monday = {"Ada", "Alex", "Maya"} and tuesday = {"Alex", "Maya", "Noah"}. What does each expression give?
For each row, pick its match from the list, then check.
sorted(monday & tuesday)sorted(monday | tuesday)sorted(monday - tuesday)sorted(tuesday - monday)len(monday | tuesday)"Noah" in mondayNow you have four structures. When you meet a new piece of data, four questions decide which one to choose: Does the order matter? Will the contents change later? Can the same value repeat? Will you reach a value by a name? Ask the questions in order and find the column in the table below that matches the answers.
| Question | List [ ] | Tuple ( ) | Set { } | Dictionary {k: v} |
|---|---|---|---|---|
| Is the order kept? | Yes | Yes | No | Insertion order |
| Does it change later? | Yes | No | Yes | Yes |
| Can there be repeats? | Yes | Yes | No | A key does not repeat |
| How do you reach an element? | Index | Index or unpacking | Only in | By key |
| Typical use in the café | The order of a table's items | (latitude, longitude) |
Try it with an example. The items of Table 4 will be kept in arrival order, the same product can come twice, and new orders will be added: the order matters, it will change, there are repeats; the answer is a list. The café's location is made of two numbers and will never change: a tuple. Today's visitors will be counted and nobody will be counted twice: a set. The price will be reached from the product name: a dictionary.
Compare the list of records from lesson 28 with a list of tuples in the same way. ("latte", 2, 4.25) is short and does not change, but what was s[2], the quantity or the price? In a dictionary record you write s["price"] and the code explains itself. When the number of fields goes past two or three, or when the fields will change later, a dictionary record is easier to read; for short, fixed pairs a tuple is enough.
Example 6 (outside the case): Taken seats in a cinema
taken = {(3, 7), (3, 8), (5, 2)}
request = (3, 8)
print(request in taken)
row, seat = request
print(f"Row {row}, seat {seat}")OutputTrue
Row 3, seat 8Two structures work together here. The position of a seat is a pair that does not change, so it is a tuple. The taken seats are a group without repeats, and the question "is this seat taken?" is asked all the time, so it is a set. Because a tuple can go into a set, the question (3, 8) in taken works directly.
Choose the most suitable structure for each scenario.
For each row, pick its match from the list, then check.
Now try it yourself in another context. A sports club has two teams. First run the two lines. Then do three things: add a line that finds only the people who play basketball; add the line volleyball.add("Marco") before the first print, and predict the new output of the first line before you run it; at the end write print(volleyball[0]) and read the error message.
Try it now· not graded; doesn't affect progress
Two concepts together: the function returns the day's summary as a tuple and it is unpacked; the customer book is turned into a set and the two days are compared.
day = [("latte", 2, 4.25), ("tea", 3, 1.25), ("latte", 1, 4.25), ("water", 2, 0.75)] def day_summary(orders): total = 0 for product, quantity, price in orders: total += quantity * price return total, len(orders) # 1. Get the summary and unpack it revenue, order_count = day_summary(day) print(f"Revenue: ${revenue:.2f}, {order_count} orders") # 2. Drop the repeats monday = set(["Ada", "Alex", "Ada", "Maya", "Alex"]) print("Different customers:", len(monday)) # 3. Compare the two days tuesday = {"Alex", "Maya", "Noah"} print("Came on both days:", sorted(monday & tuesday))
OutputRevenue: $18.00, 4 orders
Different customers: 3
Came on both days: ['Alex', 'Maya']Assigning to a tuple. If you try to change an element of a tuple out of list habit, Python stops:
product = ("latte", 4.25)
product[1] = 4.50Error:
OutputTypeError: 'tuple' object does not support item assignmentThe right way is to assign a new tuple: product = ("latte", 4.50). If the contents will change often, you should choose a list from the start.
Writing `{}` for an empty set. Curly braces write a set, but an empty {} is an empty dictionary; a dictionary has no add method:
arrived = {}
arrived.add("Ada")Error:
OutputAttributeError: 'dict' object has no attribute 'add'The right way is arrived = set(). The word 'dict' in the error message is the clue: what you hold is not a set but a dictionary.
("latte", 4.25) is ordered but cannot be changed; the comma builds a tuple ((5,)), and a tuple can be a dictionary key and a set element. name, price = product unpacks the elements in order, and return a, b returns two values as one tuple.set(items) drops repeats, in is fast, and & | - compare two groups (in difference the order matters); the empty set is set(), and use sorted to see it in order.Next lesson: So far we have made a new list from a list (a price rise, filtering) with an empty list, a loop, and append; in the next lesson we will write the same job in one line.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
("latte", 4.25)| Customers who came today |
| Menu: product → price |
The same pattern works outside the café. The people who joined two events of a club arrive in registration order, with repeats.
chess = ["Elena", "Marco", "Elena", "Noah"] hiking = ["Noah", "Zara", "Noah"] a, b = set(chess), set(hiking) print(len(a), len(b)) print(sorted(a - b)) print(sorted(a | b))
Output3 2
['Elena', 'Marco']
['Elena', 'Marco', 'Noah', 'Zara']The third line unpacks two sets into two variables in one line: the right side is a tuple. a - b gives only those who joined chess.