← 输入框|python.land|刷新

Python Tuple: How to Create, Use, and Convert

A Python tuple is one of Python’s three built-in sequence data types, the others being lists and range objects. A Python tuple shares a lot of properties with the more commonly known Python list:

  • It can hold multiple values in a single variable
  • It’s ordered: the order of items is preserved
  • A tuple can have duplicate values
  • It’s indexed: you can access items numerically
  • A tuple can have an arbitrary length

But there are significant differences:

  • A tuple is immutable; it can not be changed once you have defined it.
  • A tuple is defined using optional parentheses () instead of square brackets []
  • Since a tuple is immutable, it can be hashed, as long as all its items are hashable too. That means a tuple can act as the key in a dictionary or as an item in a set

Creating a Python tuple

We create tuples from individual values using optional parentheses (round brackets) like this:

>>> my_numbers = (1, 2, 3)
>>> the_same = 1, 2, 3
>>> my_strings = ('Hello', 'World')
>>> my_mixed_tuple = ('Hello', 123, True)Code language: Python (python)

Like everything in Python, tuples are objects and have a class that defines them. We can also create a tuple by using the tuple() constructor from that class. It allows any Python iterable type as an argument. In the following example, we create a tuple from a list:

 tuple([0,1,2])
(0, 1, 2)Code language: Python (python)

Now you also know how to convert a Python list to a tuple!

Parentheses or tuple(): which one to use?

It’s not always easy for Python to infer if you’re using regular parentheses or if you’re trying to create a tuple. To demonstrate, let’s define a tuple holding only one item:

>>> t = (1)
>>> t
1
>>> type(t)
<class 'int'>
>>> t = (1,)
>>> t
(1,)
>>> type(t)
<class 'tuple'>Code language: Python (python)

Python sees the number one, surrounded by useless parentheses on the first try, so Python strips down the expression to the number 1. However, we added a comma in the second try, explicitly signaling to Python that we are creating a tuple with just one element.

A tuple with just one item is useless for most use cases, but it demonstrates how Python recognizes a tuple: because of the comma. The one exception is the empty tuple, which you write as a pair of empty parentheses: ().

If we can use tuple(), why is there a second method as well? The other notation is more concise, but it also has its value because you can use it to unpack multiple lists into a tuple in this way concisely:

 l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> t = (*l1, *l2)
>>> t
(1, 2, 3, 4, 5, 6)Code language: Python (python)

The leading * operator unpacks the lists into individual elements. It’s as if you would have typed them individually at that spot. This unpacking trick works for all iterable types if you were wondering!

So which one should you use? Use the comma notation, with or without parentheses, when you write down the values yourself. Use tuple() when you want to convert something that already exists, like a list, a string or another iterable, into a tuple.

Multiple assignment using a Python tuple

You’ve seen something called tuple unpacking in the previous topic. There’s another way to unpack a tuple, called multiple assignment. It’s something that you see used a lot, especially when returning data from a function, so it’s worth taking a look at this.

Multiple assignment works like this:

 person = ('Erik', 38, True)
>>> name, age, registered = person
>>> name
'Erik'Code language: Python (python)

Like using the *, this type of unpacking works for all iterable types in Python, including lists and strings.

As I explained in the Python trick on returning multiple values from a Python function, unpacking tuples works great in conjunction with a function that returns multiple values. It’s a neat way of returning more than one value without having to resort to data classes or dictionaries:

def get_user_by_id(userid):
    # fetch user from database
    # ....
    return name, age
 
name, age = get_user_by_id(4)Code language: Python (python)

Indexed access

We can access a tuple using index numbers like [0] and [1]:

 my_mixed_tuple = 'Hello', 123, True
>>> my_mixed_tuple[0]
'Hello'
>>> my_mixed_tuple[2]
TrueCode language: Python (python)

Append to a Python tuple

Because a tuple is immutable, you can not append data to a tuple after creating it. For the same reason, you can’t remove data from a tuple either. You can, of course, create a new tuple from the old one and append the extra item(s) to it this way:

>>> t1 = (1, 2, 3)
>>> t = (*t1, 'Extra', 'Items')
>>> t
(1, 2, 3, 'Extra', 'Items')Code language: Python (python)

What we did was unpack t1, create a new tuple with the unpacked values and two different strings and assign the result to t again.

Get tuple length

The len() function works on Python tuples just like it works on all other iterable types like lists and strings:

 t = 1, 2, 3
>>> len(t)
3Code language: Python (python)

Tuple methods: count() and index()

Because a tuple can’t change, it has only two methods. count() tells you how often a value occurs, and index() gives you the position of the first occurrence of a value:

 t = (1, 2, 2, 3, 2)
>>> t.count(2)
3
>>> t.index(3)
3
>>> t.index(9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    t.index(9)
    ~~~~~~~^^^
ValueError: tuple.index(x): x not in tupleCode language: Python (python)

As you can see, index() raises a ValueError when the value isn’t in the tuple. If you’re not sure, check first with if 9 in t:.

Comparing and sorting tuples

Python compares tuples item by item, from left to right. The first pair of items that differs decides the result:

 (1, 2, 3) < (1, 2, 4)
True
>>> (1, 9) < (2, 0)
TrueCode language: Python (python)

This makes sorting a list of tuples easy. By default, sorted() sorts on the first item, then on the second, and so on. If you want to sort on another item, pass a key function:

 people = [('Erik', 38), ('Anna', 25), ('Bob', 38)]
>>> sorted(people)
[('Anna', 25), ('Bob', 38), ('Erik', 38)]
>>> sorted(people, key=lambda p: p[1])
[('Anna', 25), ('Erik', 38), ('Bob', 38)]Code language: Python (python)

Using a tuple as a dictionary key

Because tuples are hashable, you can use them as dictionary keys. That’s handy for keys that consist of more than one value, like coordinates:

>>> locations = {(52.37, 4.90): 'Amsterdam', (51.92, 4.48): 'Rotterdam'}
>>> locations[(52.37, 4.90)]
'Amsterdam'Code language: Python (python)

There’s a catch, though. A tuple is only hashable if everything inside it is hashable. A tuple that contains a list can’t be a key, because the list inside it can still change:

>>> d = {}
>>> d[(1, [2])] = 'oops'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d[(1, [2])] = 'oops'
    ~^^^^^^^^^^
TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')Code language: Python (python)

Named tuples

With a regular tuple, you need to remember what each position means. Is person[1] the age or the name? A named tuple solves this by giving each position a name. You can still use it like any other tuple. The collections module has the classic version:

 from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(3, 4)
>>> p
Point(x=3, y=4)
>>> p.x
3
>>> p[1]
4
>>> x, y = p
>>> p.x = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    p.x = 10
    ^^^
AttributeError: can't set attributeCode language: Python (python)

The more modern way is typing.NamedTuple. You write it as a class with type hints, and you can give fields a default value:

from typing import NamedTuple

class Person(NamedTuple):
    name: str
    age: int
    registered: bool = False

erik = Person('Erik', 38)
print(erik)      # Person(name='Erik', age=38, registered=False)
print(erik.age)  # 38

# A named tuple can't change, but you can create a changed copy:
print(erik._replace(age=39))  # Person(name='Erik', age=39, registered=False)Code language: Python (python)

If you need an object that you can change, or one with methods, look at data classes instead.

Python tuple vs list

The most significant difference between a Python tuple and a Python list is that a List is mutable, while a tuple is not. After defining a tuple, you can not add or remove values. In contrast, a list allows you to add or remove values at will. This property can be an advantage; you can see it as write protection. If a piece of data is not meant to change, using a tuple can prevent errors. After all, six months from now, you might have forgotten that you should not change the data. Using a tuple prevents mistakes.

Tuples are also a little smaller and faster to create. In CPython, both a list and a tuple are arrays of references to objects. A list keeps some spare room so it can grow, while a tuple has a fixed size, so it needs less memory:

>>> import sys
>>> sys.getsizeof((1, 2, 3, 4, 5))
88
>>> sys.getsizeof([1, 2, 3, 4, 5])
104Code language: Python (python)

A tuple of constants, like (1, 2, 3, 4, 5), is created only once, when Python compiles your code. A list has to be built each time. On my machine, with Python 3.15, that makes creating this tuple about nine times faster (3.7 versus 33 nanoseconds, measured with python3 -m timeit). Reading an item by index is equally fast for both. In practice, these differences rarely matter, so choose between a list and a tuple based on whether the data should be able to change.

Python tuple vs set

The most significant difference between tuples and Python sets is that a tuple can have duplicates while a set can’t. The entire purpose of a set is its inability to contain duplicates. It’s an excellent tool for deduplicating your data.

Converting Python tuples

Convert tuple to list

Python lists are mutable, while tuples are not. If you need to, you can convert a tuple to a list with one of the following methods.

The cleanest and most readable way is to use the list() constructor:

 t = 1, 2, 3
>>> list(t)
[1, 2, 3]Code language: Python (python)

A more concise but less readable method is to use unpacking. This unpacking can sometimes come in handy because it allows you to unpack multiple tuples into one list or add some extra values otherwise:

>>> t = 1, 2, 3
>>> l = [*t]
>>> l
[1, 2, 3]
>>> l = [*t, 4, 5, 6]
>>> l
[1, 2, 3, 4, 5, 6]Code language: Python (python)

Convert tuple to set

Analogous to the conversion to a list, we can use set() to convert a tuple to a set:

 t = (1, 2, 3)
>>> s = set(t)
>>> s
{1, 2, 3}Code language: Python (python)

Here, too, we can use unpacking:

>>> s = {*t}
>>> s
{1, 2, 3}Code language: Python (python)

Convert tuple to string

Like most objects in Python, a tuple has a so-called dunder method, called __str__, which converts the tuple into a string. When you want to print a tuple, you don’t need to do so explicitly. Python’s print function will call this method on any object that is not a string. In other cases, you can use the str() constructor to get the string representation of a tuple:

 t = (1, 2, 3)
>>> print(t)
(1, 2, 3)
>>> str(t)
'(1, 2, 3)'
Code language: Python (python)

Related articles