Codiqo

Learn Python · lesson 29 of 60 · about 7 minutes

Tuples and Sets

Set the assistant's alarm with a tuple, and plan the shops on the way with a set, so each one is visited only once.

What you'll learn

  • Create and unpack tuples
  • Remove duplicates with a set
  • Test membership quickly

An alarm and some shops

The assistant now sets Sam's alarm. A time is two numbers that belong together, an hour and a minute, so it's kept as one tuple, (7, 30), and unpacked into hour and minute. Then Sam types the shops on the way, like bakery bank bakery post. The bakery comes up twice, but Sam only needs to go once: a set keeps each shop a single time.

Tuples: fixed groups

A tuple is like a list that can't change, written with round brackets: (3, 4). Use it for values that belong together, like a coordinate.

You can unpack a tuple straight into separate variables.

A point on a map

point = (3, 7)
x, y = point
print(x, y)
print(point[0] + point[1])

Output

3 7
10

Sets: no duplicates

A set holds each value only once, written with curly braces: {1, 2, 3}. Turning a list into a set removes the repeats. Sets have no order, so sort them if you need to print them neatly.

Unique visitors

visits = ["ada", "bo", "ada", "cy", "bo"]
unique = set(visits)
print(len(unique))
print(sorted(unique))
print("cy" in unique)

Output

3
['ada', 'bo', 'cy']
True

Tip

An empty pair of braces {} makes an empty dictionary, not a set. Use set() for an empty set.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.