Lesson 15 of 35Python
Python · Lesson 15 · 30 minutes
Tuples and sets
What you'll learn
- Use tuples as unchangeable pairs of values
- Remove duplicate values with sets
- Form intersections, unions and differences
Tuples: values that belong together
A tuple looks like a list, just with round brackets. The big difference: you can’t change it. That suits things that belong together for good – a coordinate, a date, a colour:
point = (3, 7)
print(point[0], point[1])
# Unpacking: give every value a name
x, y = point
print("x =", x, "y =", y)
colour = (255, 128, 0)
red, green, blue = colour
print(red + green + blue)Python uses tuples a lot behind the scenes – for example when a function returns two values:
def min_max(numbers):
return min(numbers), max(numbers)
smallest, biggest = min_max([4, 9, 1, 7])
print(smallest, biggest)Sets: every value only once
A set is written with curly braces. It has no fixed order and contains every value only once:
visitors = ["Ana", "Ben", "Ana", "Cem", "Ben"]
unique = set(visitors)
print(unique)
print(len(unique), "different visitors")
print("Cem" in unique)Calculating with sets
These signs only work with sets. If you have lists, turn them into sets with set(...) first.
| Sign | Name | Meaning |
|---|---|---|
a & b | intersection | in both |
a | b | union | in at least one |
a - b | difference | in a but not in b |
football = {"Ana", "Ben", "Cem"}
chess = {"Cem", "Dora", "Ana"}
print("both:", football & chess)
print("either:", football | chess)
print("only football:", football - chess)Quick check
Before you start the task: what does this program print?
numbers = [5, 3, 5, 1, 3]
print(len(numbers), len(set(numbers)))Your task
Your turn
Write two functions. different(lst) returns how many different values are in the list. common(a, b) gets two lists and returns a sorted list of the values that appear in both (each only once). Use sets for this. Careful: & only works with sets, not with lists – a & b gives an error here. So turn each list into a set first.
def different(lst):
pass
def common(a, b):
pass
print(different([1, 2, 2, 3, 3, 3]))
print(common(["Ana", "Ben", "Cem"], ["Cem", "Dora", "Ana"]))- Something to think about
set(lst)removes all duplicates –len()of that is the number you want. - Which command helps?
Turn both lists into sets and intersect them with
&.sorted(...)turns that into a sorted list. - Gap code – fill in the ___
def different(lst): return ___ def common(a, b): return ___ print(different([1, 2, 2, 3, 3, 3])) print(common(["Ana", "Ben", "Cem"], ["Cem", "Dora", "Ana"]))
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
def different(lst):
return len(set(lst))
def common(a, b):
return sorted(set(a) & set(b))
print(different([1, 2, 2, 3, 3, 3]))
print(common(["Ana", "Ben", "Cem"], ["Cem", "Dora", "Ana"]))