Start learning free

LESSON 260 OF 673 · TUPLES, SORTING & BUILT-INS

Tuples in Python

Lesson

TL ; DR:

A tuple keeps a few values together, like a movie's title and year. Read a value by its position, or unpack them all into variables.


movie = ("Frozen", 2013)   # a tuple
print(movie[0])            # Frozen
print(movie[1])            # 2013

title, year = movie        # unpacking
print(title, year)         # Frozen 2013

def firstAndLast(word):
    return word[0], word[-1]

first, last = firstAndLast("code")
print(first, last)         # c e


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. A tuple keeps a few values like these in one variable.

  • movie = ("Frozen", 2013) makes a tuple. The values go in parentheses, separated by commas.
  • movie[0] is the first value, "Frozen". movie[1] is the second, 2013.
  • len(movie) is 2, as for a list.

Unpacking gives each value its own name. title, year = movie puts "Frozen" in title and 2013 in year. You need one name per value.

You have unpacked before. In for name, points in scores.items(), each key and value comes as a tuple.

A function can return a tuple. return a, b returns two values at once. The caller unpacks them: x, y = f().

In a function's header, Tuple[str, int] means a tuple of a str and an int. It works like List[int].

A tuple can't be changed. movie[1] = 2014 stops with a TypeError. To change a value, build a new tuple: movie = (movie[0], 2014).

So when do you pick which? A list holds many values of one kind, and it can grow. A tuple holds a fixed few, often of different kinds.


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make splitTime return two values: the whole hours and the minutes left.

Then unpack pet into name and age.

Last, call splitTime(135). Unpack its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check