What Is?

What Is a Tuple in Python Programming?

In Python, a tuple is a data type closely related to the list, a very flexible sequential data type that can accommodate arbitrarily long sequence of elements.

 

Unlike the list, the tuple is immutable, which opens the possibility of calculating hash values for tuples. This property is important for the use of tuples in combination with data types like the dictionary or the set, which are based on hash tables. Based on the condition that hash values can also be calculated for all elements of a tuple, it may therefore be used as a key in a dictionary or as an element in a set, which differentiates it from a list.

 

The concept of a tuple is related to that of the list, but due to its immutability, only the basic set of operations for sequential data types is available for tuple instances.

 

To create new tuple instances, you must use the parentheses, which—like lists—contain the elements of the tuple, separated by commas:

 

>>> a = (1, 2, 3, 4, 5)

>>> a[3]

4

 

An empty tuple is defined by two parentheses () without content. A special case involves tuples with only one element. If you try to create a tuple with only one element in the way described previously, the program will behave differently than intended:

 

>>> no_tuple = (2)

>>> type(no_tuple)

<class 'int'>

 

With (2), no new tuple instance is created because the parentheses are already used in this context for arithmetic operations with integers. Hence tuple literals containing only a single element are written with an additional comma after the element:

 

>>> a_tuple = (2,)

>>> type(a_tuple)

<class 'tuple'>

 

Packing and Unpacking

You can omit the enclosing parentheses in a tuple definition. Nevertheless, the references separated by commas are combined into a tuple, which is referred to as tuple packing or, more simply, packing:

 

>>> date = 7, 26, 1987

>>> date

(7, 26, 1987)

 

Conversely, it’s also possible to unpack the values of a tuple:

 

>>> date = 7, 26, 1987

>>> (month, day, year) = date

>>> month

7

>>> day

26

>>> year

1987

 

This process is referred to as tuple unpacking or simply unpacking, and again the parentheses can be omitted. By combining packing and unpacking, you can very elegantly swap the values of two variables without a helper variable or combine several assignments in one line:

 

>>> a, b = 10, 20

>>> a, b = b, a

>>> a

20

>>> b

10

 

Unpacking is not limited to the tuple data type, but works for sequential data types in general. In this case, the term sequence unpacking is also commonly used:

 

>>> a, b, c = "abc"

>>> a

'a'

 

If applied properly, the use of this feature can contribute to the readability of programs as the technical detail of caching data moves to the background of the actual intent of swapping values.

 

Unpacking can also be used to read values at the beginning and end of a sequence. Let's consider the following example:

 

>>> numbers = [11, 18, 12, 15, 10]

>>> eleven, *others, ten = numbers

>>> eleven

11

>>> ten

10

>>> others

[18, 12, 15]

 

If an asterisk (*) is prefixed to a reference when unpacking, all other values of the sequence are stored in it. In the preceding example, the first value of numbers is stored in eleven and the last value in ten. The numbers in between are collected into others.

 

Any number of other references may precede and follow the asterisked entry. In particular, the first or last entry can have an asterisk:

 

>>> numbers = [11, 17, 17, 19, 10]

>>> *something, nineteen, ten = numbers

>>> nineteen

19

>>> ten

10

>>> eleven, *blah_blah_blah = numbers

>>> eleven

11

>>> blah_blah_blah

[17, 17, 19, 10]

 

There can always only be exactly one reference with an asterisk in an assignment with unpacking. This makes sense, as otherwise ambiguities can arise.

 

In general, you should be careful when using unpacking for unordered data types. In the following example, the order of the elements 1, 2, and 3 depends on the order in which the set {3,1,2} is iterated over:

 

>>> a, b, c = {3, 1, 2}

>>> a, b, c

(1, 2, 3)

 

Because this order is an implementation detail, it may differ between different versions of Python, or even between different runs of the same program.

 

Immutable Doesn’t Necessarily Mean Unchangeable!

Although tuple instances are immutable, the values of the elements contained during their generation may change. When a new tuple is created, the references it is to store are specified. If such a reference points to an instance of a mutable data type, such as a list, its value can still change:

 

>>> a = ([],)

>>> a[0].append("And yet it moves!")

>>> a

(['And yet it moves!'],)

 

The immutability of a tuple thus refers only to the references it contains and explicitly not to the instances behind it.

 

Thus, the fact that tuples are immutable is no guarantee that elements won’t change once the tuple has been created.

 

Editor’s note: This post has been adapted from a section of the book Python 3: The Comprehensive Guide by Johannes Ernesti and Peter Kaiser.

Recommendation

Python 3: The Comprehensive Guide
Python 3: The Comprehensive Guide

Ready to master Python? Learn to write effective code, whether you’re a beginner or a professional programmer. Review core Python concepts, including functions, modularization, and object orientation, and walk through the available data types. Then dive into more advanced topics, such as using Django and working with GUIs. With plenty of code examples throughout, this hands-on reference guide has everything you need to become proficient in Python!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments