Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

How to make a tuple

Share
Copied to clipboard.
Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
5 min. read 4 min. video Python 3.9—3.13

What are tuples and how can you make them?

Making tuples in Python

Here's a list named coordinates:

>>> coordinates = [3, 4, 5]
>>> type(coordinates)
<class 'list'>

It's a list because we used square brackets ([...]) to make it.

If we had used parentheses ((...)) instead, we would've made a tuple:

>>> coordinates = (3, 4, 5)
>>> type(coordinates)
<class 'tuple'>
>>> coordinates
(3, 4, 5)

Tuples are like lists, but immutable

Like a list, a tuple can be indexed:

>>> coordinates[0]
3

A tuple can be sliced:

>>> coordinates[1:]
(4, 5)

And you can get the length of a tuple:

>>> len(coordinates)
3

Unlike a list though, you can't update values, add new values, or delete values in a tuple:

>>> coordinates[0] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Tuples are immutable, meaning they can't be mutated (they can't be changed). So you can make new tuples, but you cannot update an existing tuple.

Tuples are all over the place

Tuples pop up all over the place in Python.

For example, the built-in enumerate function accepts an iterable and returns a new iterable of two-item tuples, where the first item is a number counting upward:

>>> colors = ["pink", "purple", "green", "blue"]
>>> for item in enumerate(colors):
...     print(item)
...
(0, 'pink')
(1, 'purple')
(2, 'green')
(3, 'blue')

The dictionary items method also returns an iterable of tuples:

>>> color_ratios = {'pink': 0.2, 'purple': 0.4, 'green': 0.3, 'blue': 0.1}
>>> for item in color_ratios.items():
...     print(item)
...
('pink', 0.2)
('purple', 0.4)
('green', 0.3)
('blue', 0.1)

In each of those tuples the first item is a dictionary key and the second item is the corresponding value.

The parentheses are optional: it's the commas that make the tuple

Note that it's actually not the parentheses that make a tuple; you can leave off those parentheses. It's the commas that make a tuple.

If you stick commas between a couple of values in Python, you've just made a tuple:

>>> coordinates = 3, 4, 5
>>> coordinates
(3, 4, 5)

The parentheses are only necessary when those commas might otherwise be ambiguous. For example, if we were making a list of two two-item tuples, we need those parentheses:

>>> points = [(1, 2), (3, 4)]

If we removed the parentheses here, we've instead made a list of four items:

>>> points = [1, 2, 3, 4]

And that's definitely not the same as a list of two tuples.

When should you make a tuple?

While tuples are immutable, their immutability isn't the primary reason that we use them. We mostly use tuples to distinguish list-like data from tuple-like data.

List-like data tends to be all of the same type and there's often lots of it. Tuple-like data is often of different types, and there's a fixed quantity of it. Meaning the first thing in a tuple usually represents something very different from the second thing in a tuple.

Let's look at some examples.

This is a list of words, each represented as with a string:

words = [
    "admire",
    "awake",
    "cherish",
    "create",
    "delight",
    "enjoy",
    "explore",
    "glow",
    "inspire",
    "journey",
    "laugh",
    "marvel",
    "meander",
    "observe",
    "play",
    "ponder",
    "question",
    "replenish",
    "travel",
    "wander",
]

There are lots of strings in this list; we don't really care exactly how many. Each of these strings mean the same thing: they're all just words.

This is a list of tuples:

cities = [
    ("Puerto Vallarta", 530_078),
    ("Belfast", 634_594),
    ("Wroclaw", 642_085),
    ("Oslo", 1_056_180),
    ("San Diego", 1_427_720),
    ("Perth", 2_067_333),
    ("Lisbon", 2_971_587),
    ("Kiev", 3_000_604),
    ("Puebla", 3_244_710),
    ("Nairobi", 4_922_192),
    ("Pune", 6_807_984),
    ("Baghdad", 7_323_079),
    ("Nanjing", 9_143_980),
    ("Lima", 10_882_757),
    ("Paris", 11_078_546),
    ("Manila", 14_158_573),
    ("Osaka", 19_110_616),
]

Each of these tuples has exactly two things in it, and the first thing represents something quite different from the second thing.

>>> sd = cities[4]
>>> sd
('San Diego', 1427720)

The first thing represents a city name (as a string):

>>> sd[0]
'San Diego'

The second thing represents the population of that city:

>>> sd[1]
1427720

If any of these tuples had more than two things or fewer than two things, our code would probably break. We're assuming we have two-item tuples here.

So tuples tend to have a known length and the position of each item in a tuple very much matters.

Returning multiple values from a function

One of the most common use cases for a tuple is to return multiple values from a function.

You can't actually return multiple values from a function in Python. But there's nothing stopping you from returning one value that's actually a conglomeration of multiple values. For example, you can return a list of values or a tuple of values.

Here we have a function named count_parity:

def count_parity(numbers):
    evens = odds = 0
    for n in numbers:
        if n % 2 == 0:
            evens += 1
        else:
            odds += 1
    return evens, odds

This function returns two values in a tuple: the number of evens and the number of odds found in the given iterable.

>>> count_parity([2, 1, 3, 4, 7, 11])
(2, 4)

By the way, that function call is a prime use case for tuple unpacking in Python.

Summary

Tuples are immutable sequences, meaning they're like lists, but we can't change them.

Unlike lists, we usually use tuples to store a fixed number of values, sometimes of different types. And the position of the values in a tuple is significant (i.e. the first thing in a tuple tends to represent something different from the second thing).

5 Keys to Python Success 🔑

Sign up for my 5 day email course and learn essential concepts that introductory courses often overlook!