A Python tuple is one of Python’s three built-in sequence data types, the others being lists and range objects. A Python tuple is almost identical to a 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
The only differences:
- A tuple is immutable; it can not be changed once you defined it.
- A tuple is defined using parentheses () instead of square brackets []
Creating a Python tuple
We create tuples from individual values using parentheses (round brackets) like this:
>>> my_numbers = (1, 2, 3)
>>> my_strings = ('Hello', 'World')
>>> my_mixed_tuple = ('Hello', 123, True)
Like everything in Python, tuples are objects and have a class that defines them. A tuple can also be created 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)
>>>
Now you know how to convert a Python list to tuple as well!
Which method is best?
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)
1
>>> t = (1, )
(1,)
In the fist try, Python sees the number one, surrounded by useless parentheses, so Python strips down the expression to the number 1. In the second try, however, we added a comma, 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. If you want to be absolutely certain that you are creating a tuple, you can always use the tuple()
constructor.
If we can use tuple()
, why is there a second method as well? The other notation obviously is more concise, but it also has its value because you can use it to concisely unpack multiple lists into a tuple, in this way:
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> t = (*l1, *l2)
>>> t
(1, 2, 3, 4, 5, 6)
The leading *
operator unpacks the lists into individual elements. This unpacking trick works for all iterable types, if you were wondering!
Multiple assignment using a Python tuple
There’s another way of unpacking a tuple, or any other iterable, as well. It’s useful when assigning multiple variables at once. It works like this:
>>> person = ('Erik', 38, True)
>>> name, age, registered = person
>>> name
'Erik'
>>> _
Just 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 comes in very handy when returning multiple values from a function. 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)
Indexed access
A tuple can be accessed using index numbers like [0]
and [1]
:
>>> my_mixed_tuple = ('Hello', 123, True)
>>> my_mixed_tuple[0]
'Hello'
>>> my_mixed_tuple[2]
True
>>> _
Append to a Python Tuple
Because a tuple is immutable, you can not apend data to a tuple after it’s created. 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')
What we did is unpack t1
, create a new tuple with the unpacked values and two extra 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:
>>> t = (1, 2, 3)
>>> len(t)
3
Python Tuple vs List
The biggest difference between a tuple and a list, is the fact 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.
Python Tuple vs Set
The biggest difference between tuples and sets is the fact 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 a great tool for deduplicating your data.
Converting Python tuples
Convert Tuple to List
Python’s List, in other languages often called an array, is mutable. If you need to convert a tuple to a list, use 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]
A more concise, but less readable method is to use unpacking. This can sometimes come in handy though, 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]
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}
Here, too, we can use unpacking as well:
>>> s = {*t}
>>> s
{1, 2, 3}
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. Print 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)'
In “Append to a Python Tuple” it should read “unpack t1′ after the code example.
Thank you, fixed it!
thanks very good