Python lesson 22

Tuples and Sets

One list that cannot change, and one that refuses repeats.

Locked and Unique

A tuple looks like a list but uses round brackets, and once it is made it cannot be changed. Round brackets have meant call this function up to now. Here they hold a list of values instead. A name in front of them means a call, and nothing in front means a tuple. A set uses curly braces and silently throws away any duplicates. Curly braces made a dictionary back in lesson 20, and they make a set here. Python tells them apart by what is inside: pairs with colons make a dictionary, plain values make a set. Empty braces are a dictionary, so an empty set has to be written set(). Both are ordinary Python, and both save you from a whole class of bug.

screen = (800, 600) # a tuple. Locked
players = {"Sam", "Ada"} # a set. No repeats
scores = {"Sam": 10} # colons, so a dictionary
empty = set() # {} would be a dictionary

players.add("Sam") # already there, nothing happens

screen = (800, 600)
print("Width:", screen[0])

players = {"Sam", "Ada", "Sam"}
print("Players:", len(players))

How Many Are There?

colours = {"red", "blue", "red", "green", "blue"}
print(len(colours))

Try to Change It

screen = (800, 600)
screen[0] = 1024
print(screen)

Unpacking a Tuple

Run it. Two variables get filled from one tuple in a single line.

screen = (800, 600)
width, height = screen
print("Width is", width)
print("Height is", height)

Remove the Repeats

A list of visitors with duplicates. Turn it into a set to find out how many different people came.

visitors = ["Sam", "Ada", "Sam", "Jo", "Ada", "Sam"]
unique = set(visitors)
print("Visits:", len(visitors))
print("Different people:", len(unique))

Who Played Both Games?

Two sets of players. Find the ones who appear in both.

chess = {"Sam", "Ada", "Jo"}
maths = {"Ada", "Jo", "Nia"}
both = chess & maths
print("Played both:", both)
print("Played either:", chess | maths)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.