Start learning free

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

Tuples in Python: Packing and Unpacking

Lesson Read the full explanation

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

    PYTHON · TUPLES, SORTING & BUILT-INS

    Tuples in Python, explained

    What a tuple is

    Some values belong together: a pet's name and age, or a point's x and y. A tuple keeps a few values like these in one variable. You write the values in parentheses, separated by commas, and read each one by its position, starting from 0.

    pet = ("Rex", 4)
    print(pet[0])
    print(pet[1])
    print(len(pet))
    
    Rex
    4
    2
    

    A tuple looks like a list, but it holds a fixed few values, often of different kinds (a str and an int here). A list holds many values of one kind, and it can grow.

    Tuples show up whenever Python needs to hand back "a few things at once". A line such as pet[0] reads the first one, and negative positions work too: pet[-1] is the last value, here 4. Slicing and len behave as they do for lists, so what you know about indexing carries over.

    Unpacking

    Unpacking gives each value of a tuple its own name, in one line. The names go on the left of the =, in the same order as the values.

    name, age = pet
    print(name, age)
    
    Rex 4
    

    You need exactly one name per value. Three names for a two-value tuple stop the program with ValueError: not enough values to unpack (expected 3, got 2).

    You have already unpacked tuples without calling them that: in for name, points in scores.items(), each key and value arrives as a tuple, and the loop splits it into two names.

    Returning two values

    A function can return a tuple: return a, b packs both values, and the caller unpacks them with x, y = f(). The parentheses are optional here, because the comma is what makes the tuple.

    def firstAndLast(word):
        return word[0], word[-1]
    
    first, last = firstAndLast("code")
    print(first, last)
    
    c e
    

    In a type hint, Tuple[str, int] means a tuple of a str and an int, in that order. It plays the same role as List[int] does for a list.

    Tuples can't be changed

    Assigning to a position stops with a TypeError:

    pet[1] = 5
    
    TypeError: 'tuple' object does not support item assignment
    

    To change a value, build a new tuple: pet = (pet[0], 5) gives ('Rex', 5). One more trap: a one-value tuple needs a trailing comma. (5,) is a tuple, while (5) is just the integer 5 in parentheses.

    Choosing between a tuple and a list

    Ask what the value is. If it is "one pet" or "one point", a few parts with different jobs, use a tuple. If it is "all the pets", a collection whose size can change, use a list. Often you meet both: a list of tuples, such as [("Rex", 4), ("Bella", 7)], where each tuple is one pet and the loop for name, age in pets unpacks one pet per pass.

    The exercise, step by step

    The task has three parts, and the code already prints the three lines.

    1. Make splitTime return the whole hours, minutes // 60, and the minutes left, minutes % 60. For 135 minutes that is 2 and 15.
    2. Unpack pet into name and age.
    3. Call splitTime(135) and unpack its result into hours and mins.
    def splitTime(minutes):
        return minutes // 60, minutes % 60
    
    pet = ("Rex", 4)
    print(pet[0])
    
    name, age = pet
    print(name, "is", age)
    
    hours, mins = splitTime(135)
    print(name, "walked", hours, "h", mins, "min")
    
    Rex
    Rex is 4
    Rex walked 2 h 15 min
    

    Printing splitTime(135) directly shows (2, 15), which is one tuple.

    Key takeaways

    • A tuple groups a few values; read them with t[0], t[1].
    • Unpack with one name per value: name, age = pet.
    • return a, b returns a tuple, and the caller unpacks it.
    • A list of tuples is a common shape: loop over it and unpack each tuple in the for line.
    • Tuples can't be changed; build a new one instead.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free