Algorithms

Tuple: values that go together, like latitude and longitude

Cover of the article Tuple: values that go together, like latitude and longitude
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How do you create a tuple in Python?
  2. What’s the difference between a tuple and a list?
  3. What is unpacking?
  4. How do you swap two values?
  5. How does a function return two values?
  6. Now you ask: what about the for with two variables?
  7. What are the most common mistakes with tuples?
  8. Now it’s your turn!

A tuple is a sequence of values, separated by commas, that can’t be changed after it’s created. Unpacking is distributing the values of a sequence into several variables at once, in a single line of code.

In the article about arrays and matrices, you learned how to store several values under a single name. And in the article about functions, you saw that a function gives back a result. Now look at this line of Python: a, b = b, a. Two variables on one side, two on the other, and no list in sight. Lines like this will show up a lot in the next articles, and this one exists so that none of them stalls your reading.

Think of a point on a map. It’s made of two numbers, the latitude and the longitude, that always go together and always in the same order. If you swap one of them, it’s already another place. Nobody “edits” a point: you pick another point. That’s what a tuple is: a closed package of values, in which the position of each one has a meaning.

How do you create a tuple in Python?

Just separate the values with commas. The parentheses are optional in most cases, but they help you see where the tuple starts and ends:

point = (3, 5)
print(point)
print(point[0])
print(len(point))

colors = "blue", "green", "purple"
print(colors)

just_one = (7,)
print(just_one, len(just_one))

Output:

(3, 5)
3
2
('blue', 'green', 'purple')
(7,) 1

Look at the last line. To create a tuple with a single value, the comma is mandatory: (7,). It’s the comma that makes the tuple, not the parentheses. The official Python tutorial describes the tuple exactly like that: values separated by commas.

What’s the difference between a tuple and a list?

Both store values in order, and both use indexes starting at zero. The difference is in what happens after they’re created:

ListTuple
How you write it[3, 5](3, 5)
Can you change a value?YesNo
Can you add or remove values?YesNo
Most common useA collection of items of the same kind, which grows and changesA closed record, in which each position has a meaning
The difference between a list and a tuple in Python.

See the difference in practice:

shopping = ["rice", "beans"]
shopping[0] = "pasta"
print(shopping)

point = (3, 5)
point[0] = 10

Output (just the last line of the error message):

['pasta', 'beans']
TypeError: 'tuple' object does not support item assignment

The list accepted the change. The tuple didn’t: the program stopped with an error, and the message says the tuple doesn’t accept assignment to a position. Got it? When a set of values shouldn’t change, the tuple protects you from changing it by accident.

What is unpacking?

It’s the way back: taking the tuple and handing each value to a variable. Order rules here: the first value goes to the first variable, the second to the second.

student = ("Ana", 30)
name, age = student
print(name)
print(age)

Output:

Ana
30
Diagram of the student tuple, with Ana and 30, being unpacked into the variables name and age
Unpacking: each value of the tuple goes into a variable, following the order.

The Python tutorial calls the way there packing (several values become a tuple) and the way back unpacking. And it warns: on the left side of the equals sign, you need as many variables as the sequence has values.

IMPORTANT: unpacking works with any sequence, not just with tuples. A list with two values can also be unpacked into two variables.

How do you swap two values?

This is the use you’ll see most in sorting algorithms. Swapping two values looks simple, but there’s a trap: if you write a = b, the old value of a is gone. The classic way out is to use a third variable to hold that value. Here it is in C:

#include <stdio.h>

int main(void)
{
    int a = 5;
    int b = 3;

    int aux = a; // keeps the 5 before it gets erased
    a = b;
    b = aux;

    printf("%d %d\n", a, b);
    return 0;
}

Output:

3 5

In Python, unpacking solves it in one line:

a = 5
b = 3
a, b = b, a
print(a, b)

Output:

3 5

Python first builds the tuple on the right side, with the current values of b and a, and only then distributes them. That’s why nothing is lost. The official tutorial sums it up: multiple assignment is a combination of packing and unpacking.

Diagram comparing the swap of two values with a helper variable, in three steps, and with unpacking, in one line
The same swap done two ways: three steps with a helper variable, one line with unpacking.

In PHP the idea is the same, with square brackets:

<?php

$a = 5;
$b = 3;
[$a, $b] = [$b, $a];
echo "$a $b\n";

Output:

3 5

The PHP manual calls this feature array destructuring, and the square-bracket syntax has existed since PHP 7.1. Focus on the concept, not the language!

How does a function return two values?

A function returns only one result. But that result can be a tuple, and then several values fit inside it:

def smallest_and_largest(values):
    smallest = values[0]
    largest = values[0]
    for value in values:
        if value < smallest:
            smallest = value
        if value > largest:
            largest = value
    return smallest, largest


grades = [7.5, 8.0, 6.5, 9.0]
result = smallest_and_largest(grades)
print(result)

smallest, largest = smallest_and_largest(grades)
print(smallest)
print(largest)

Output:

(6.5, 9.0)
6.5
9.0

In the first call, the whole result went into a single variable, and print showed the tuple. In the second, the result was unpacked straight into smallest and largest. Notice that return smallest, largest doesn’t even use parentheses: the comma already builds the tuple.

Now you ask: what about the for with two variables?

That’s unpacking too! When each item of a list is a tuple, the for can open the item into two variables on each lap:

students = [("Ana", 7.5), ("Bruno", 8.5), ("Carla", 6.5)]

for name, grade in students:
    print(name, grade)

for position, student in enumerate(students):
    print(position, student[0])

Output:

Ana 7.5
Bruno 8.5
Carla 6.5
0 Ana
1 Bruno
2 Carla

The second part uses the enumerate function, which hands over two values per lap: the position and the item. The Python tutorial shows this same use, with two variables in the for.

In PHP, foreach accepts the square brackets in the same place:

<?php

$students = [["Ana", 7.5], ["Bruno", 8.5], ["Carla", 6.5]];

foreach ($students as [$name, $grade]) {
    echo "$name $grade\n";
}

Output:

Ana 7.5
Bruno 8.5
Carla 6.5

C has no tuples. To group values of different types, the language offers the struct, which is a topic for another article.

What are the most common mistakes with tuples?

  • Forgetting the comma in a one-value tuple. (5) is just the number 5 in parentheses. The tuple is (5,).
  • Unpacking with the wrong number of variables. Writing a, b = (1, 2, 3) makes the program stop with the message ValueError: too many values to unpack (expected 2): too many values for two variables.
  • Trying to change the tuple. If the set needs to change, the right choice is a list.
  • Swapping the order of the variables. Unpacking doesn’t look at the names, only at the position. In age, name = ("Ana", 30), the variable age gets “Ana”.

Check the first mistake on the list:

number = (5)
print(type(number))

one_item = (5,)
print(type(one_item))

Output:

<class 'int'>
<class 'tuple'>

Now it’s your turn!

First on paper, without running anything. The variables start like this: a = 1, b = 2 and c = 3. After the line a, b, c = c, a, b, what is the value of each one? Write down the answer and only then check it on the computer.

Then write a function that receives a list of grades and returns two things at once: the sum and the average. Call the function and unpack the result into two variables. Try it on your own, without asking anyone for the ready-made answer, not even AI!

See you in the next article!

Stay confident!!!

Sources:

  • Python Software Foundation, official tutorial. Data Structures, with the sections on tuples and sequences, packing, unpacking, multiple assignment and the use of enumerate in the for.
  • Stanford University, CS106A (Nick Parlante). Python Tuples, with the tuple as an immutable sequence and the comma that, even without parentheses, is enough to create it.
  • University of Washington, CSE 160. Tuples and sorting, with tuples defined by the comma and the tuple as a sequence that can’t be changed after it’s created.
  • Cornell University, Center for Advanced Computing. Tuples, dictionaries, sets, with tuples accessed by index like lists, but immutable.
  • University of Vermont, CS 1210 course book. Sequence unpacking, with the unpacking of tuples, the ValueError when the counts don’t match and the swap of two variables.
  • University of Waterloo, CS 114 (Think Python). Chapter 26: Tuples, with the swap that uses a temporary variable and the tuple assignment that replaces it.
  • Python for Everybody (Charles Severance), chapter 10. Tuples, with tuple assignment, which also works with a two-element list, and the for with two variables.
  • PHP, official manual. list, with the assignment of a list of variables in one operation.
  • PHP, language change proposal (RFC). Square bracket syntax for array destructuring assignment, with the square-bracket syntax for destructuring, implemented in PHP 7.1.
  • GNU, The GNU C Language Manual. Structures, with the structure as a user-defined data type that holds fields of different types.
  • The examples in this article were run on Python 3.13, PHP 8.3 and GCC 13.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).