livepython.net
CHAPTER 14Tuples and Sets
14.1  TUPLES

Python Tuples: Create, Read and Why They Can't Change

What Is a Tuple in Python?

A tuple is a collection of values in a fixed order, written in round brackets (). It looks a lot like a list from chapter 9, with one big difference: once you make a tuple, it can't change.

PYTHONedit me
point = (3, 5)
days = ("Mon", "Tue", "Wed")
print(point)
print(days)
print(type(days))
OUTPUT
(3, 5)
('Mon', 'Tue', 'Wed')
<class 'tuple'>

Think of it like the date printed on a train ticket: day, month and year, always in that order, and nobody can rub it out and write a new one.

What you already know still works

Reading a tuple works exactly like reading a list:

You writeIt gives
days[0]the first item, "Mon"
days[-1]the last item, "Wed"
days[0:2]a new tuple with the first two items
len(days)the number of items, 3
"Tue" in daysTrue
for day in days:each item in turn
PYTHONedit me
days = ("Mon", "Tue", "Wed")
print(days[0], days[-1])
print(days[0:2])
print(len(days))
print("Sun" in days)
for day in days:
    print("Open on", day)
OUTPUT
Mon Wed
('Mon', 'Tue')
3
False
Open on Mon
Open on Tue
Open on Wed

The rules

  • Items go inside round brackets, separated by commas.
  • A tuple can mix types: ("Sunny", 25, True) holds a name, an age and a yes or no.
  • When you print a tuple, Python shows the round brackets, and strings get single quotes, as with lists.
  • Indexes start at 0, and a missing index gives the same IndexError as a list.

Common beginner doubt: "Square or round brackets, does it matter?" Yes! The brackets decide the type. Square brackets [] make a list, round brackets () make a tuple. Everything else in this chapter comes from that one choice.

A tuple is a list in round brackets that can't change: same indexes, same len(), same in, same for loop.

your turnPredict the output

What will this print?

colors = ("red", "green", "blue") print(colors[1])
Your turn! What will this code show on the screen?
your turnPick the right idea

Which one is a tuple?

Think about it, then pick one.

Tuples Can't Change: What Immutable Means

A tuple is immutable, a fancy word for "can't be changed". Once it's made, you can't replace an item, add one or take one away.

PYTHONedit me
point = (3, 5)
point[0] = 10
OUTPUT
TypeError: 'tuple' object does not support item assignment

Don't be scared of this error! It's just saying: a tuple doesn't let you put a new value into one of its places. "Item assignment" means point[0] = ....

Think of it like words carved in stone. A list is a whiteboard: you can wipe and rewrite it. A tuple is the stone: you can read it as often as you like, but not rewrite it.

No append, no remove

The list methods that change a list don't exist on a tuple:

PYTHONedit me
days = ("Mon", "Tue")
days.append("Wed")
OUTPUT
AttributeError: 'tuple' object has no attribute 'append'
What you wantlisttuple
read an item: x[0]yesyes
len(), in, a for loopyesyes
change an item: x[0] = 1yesno
append(), insert(), remove(), pop(), sort()yesno

Need a different tuple? Make a new one

You can't change a tuple, but you can build a new one and store it in the same variable. + joins two tuples into a new tuple:

PYTHONedit me
days = ("Mon", "Tue")
days = days + ("Wed", "Thu")
print(days)
OUTPUT
('Mon', 'Tue', 'Wed', 'Thu')

The old tuple wasn't changed. The variable days now holds a brand-new, longer tuple, the same way score = score + 5 gave a variable a new value in chapter 4.

Why would you want that?

  • Safety. Values that must stay fixed, like the days of the week or a birth date, can't be changed by mistake somewhere in a long program.
  • A promise to the reader. A tuple says "these values belong together and stay as they are".

Good: birthday = (12, 5, 2001). A date never changes.

Avoid: cart = ("milk", "bread"). A shopping cart grows and shrinks, so use a list.

A tuple can't change. To get a different tuple, build a new one.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

Remember lists from chapter 9?

sizes = ["S", "M"] sizes.append("L") print(sizes)
Your turn! What will this code show on the screen?

One-Item Tuples Need a Comma

The comma makes a tuple, not the round brackets. So a tuple with only one item needs a comma after that item: ("Sunny",).

PYTHONedit me
a = (5)
b = (5,)
print(type(a))
print(type(b))
print(b)
OUTPUT
<class 'int'>
<class 'tuple'>
(5,)

Why? Round brackets already have a job: they group maths, like (2 + 3) * 4 in chapter 5. So (5) is the number 5 in brackets, nothing more. The comma is what tells Python "this is a tuple".

Think of it like a parcel: the brackets are the box, but the comma is the label that says "tuple". A box with no label is just a box.

The rules

  • (5) is the int 5.
  • (5,) is a tuple with one item.
  • () is an empty tuple.
  • Python prints a one-item tuple with its comma: (5,).

Tuples without brackets

Because the comma does the work, you can even leave the brackets out:

PYTHONedit me
point = 3, 5
print(point)
print(type(point))
OUTPUT
(3, 5)
<class 'tuple'>

This is called packing: Python packs the values into a tuple. You'll see in the next topic why this matters: it's the secret behind swapping two variables. Most of the time, though, write the brackets. They make the tuple easy to see.

Common mistake: the missing comma

Without the comma, you don't get an error. You get something else, which is worse:

PYTHONedit me
names = ("Sunny")
print(len(names))
OUTPUT
5

You wanted a tuple with one name, so you expected 1. But names is the string "Sunny", and len() counted its 5 letters. When a one-item tuple acts strangely, look for the missing comma.

PYTHONedit me
names = ("Sunny",)
print(len(names))
OUTPUT
1

One item? Add a comma: ("Sunny",). The comma makes the tuple.

your turnFill the gap

Make a tuple with one item

colors = ? print(type(colors), len(colors))

It should print: <class 'tuple'> 1

Which piece makes this code work?
your turnType the output

Type what this prints

x = (7) print(x * 2)
Read the code line by line, then type the output exactly.

Tuple Methods: count() and index()

A tuple has only two methods, because it can't change: count() tells you how many times a value appears, and index() tells you where it first appears.

PYTHONedit me
rolls = (6, 2, 6, 4, 6)
print(rolls.count(6))
print(rolls.index(4))
OUTPUT
3
3

6 appears three times. 4 first appears at index 3 (remember, counting starts at 0).

Think of a scoreboard behind glass: you can read it, count things on it and point at a place on it, but you can't write on it.

The rules

  • t.count(x) gives how many times x is in the tuple, or 0 if it's not there.
  • t.index(x) gives the index of the first x. If x isn't there, it's an error.
  • Lists have both methods too.

Avoid: index() of a missing value

PYTHONedit me
rolls = (6, 2, 6)
print(rolls.index(5))
OUTPUT
ValueError: tuple.index(x): x not in tuple

The error says exactly what happened: the value you asked for is not in the tuple.

Good: check with in first

An if from chapter 8 keeps you safe:

PYTHONedit me
rolls = (6, 2, 6)
if 5 in rolls:
    print(rolls.index(5))
else:
    print("No 5 rolled")
OUTPUT
No 5 rolled

The usual helpers work too

Everything that only reads a collection works on a tuple: min(), max(), sum() and sorted().

PYTHONedit me
temps = (31, 28, 35, 30)
print(max(temps), min(temps), sum(temps))
print(sorted(temps))
print(temps)
OUTPUT
35 28 124
[28, 30, 31, 35]
(31, 28, 35, 30)

Look closely: sorted() gives back a list in square brackets. The tuple itself stays exactly as it was, because it can't change. There's no temps.sort(): that method would change the tuple.

A tuple can be read and counted, never changed: count(), index(), min(), max(), sum() and sorted() all work.

your turnPredict the output

What will this print?

t = (1, 2, 2, 3, 2) print(t.count(2))
Your turn! What will this code show on the screen?
your turnFix the code

Fix the code so it prints: Not found

It should print: Not found

letters = ("a", "b")
print(letters.index("c"))
This code does not work yet. Fix it, then press Run.

Practice: Tuples

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 120.Python Program to Find the Day Name from a Number Using a TupleEasySolve
  2. 121.Python Program to Find the Day of the Year Using a TupleMediumSolve