Tuples & sets
A tuple is like a list that can never change. It uses round brackets and is great for fixed groups like coordinates. Unpacking splits it into variables:
point = (3, 4) x, y = point
A set keeps only unique items, in no particular order:
set(["a", "b", "a"]) # {'a', 'b'} {1, 2} & {2, 3} # {2} in both {1, 2} | {2, 3} # {1, 2, 3} either {1, 2} - {2, 3} # {1} in the first but not the second
Use set() for an empty set ({} is an empty dictionary). cities.add("Oslo") adds one item to a set; adding the same item again has no effect. "Oslo" in cities tests membership. cities.discard("Oslo") removes an item if it is there and quietly does nothing if not; cities.remove("Oslo") raises a KeyError for a missing item.
Tuples are immutable: point[0] = 5 raises a TypeError. To change one, copy it into a list, change the list, and convert back:
cells = list(point) # [3, 4] cells[0] = 5 point = tuple(cells) # (5, 4)
See it run
colors = {"red", "blue"}
colors.add("red")
colors.add("green")
a, b = 1, 2
a, b = b, a
print(len(colors), a, b)A set never keeps duplicates, and a tuple can be unpacked into several names at once.
Practice tuples & sets
Exercise 1
Use point and tags in the editor below.
- Unpack
pointintoxandy, then makedist= √(x² + y²) using** 0.5(5.0). - Make
uniquethe set oftagsandcountits size.
Exercise 2
Use the chess and drama club sets in the editor below. Using set operators:
both= students in both clubsany_club= everyone in at least one clubonly_chess= students in chess but not drama (use-)
Exercise 3
Use routes in the editor below. Each route is a tuple (start, end, km). Loop with for start, end, km in routes: to:
- add up
total_km - build
cities, a set of every city mentioned (use.add)
Exercise 4
The start tuple in the editor below holds a robot's (x, y, heading). Its second line tries to change x in place and crashes with a TypeError, because tuples are immutable. Replace that line: copy start into a list, set index 0 to 5, and convert back so moved is the tuple (5, 2, "N"). Leave start unchanged.
Exercise 5
A gym logs every check-in in visits (names repeat).
members= the set of distinct names, made withset(visits)came_ana= whether"Ana"is inmembers(usein)- Bo cancelled: remove
"Bo"with.discard, then also discard"Zed", who never visited unique_count= how many members remain
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.