Python's tuple Data Type: A Deep Dive With Examples

Python's tuple Data Type: A Deep Dive With Examples

by Leodanis Pozo Ramos Oct 04, 2023 intermediate python

In Python, a tuple is a built-in data type that allows you to create immutable sequences of values. The values or items in a tuple can be of any type. This makes tuples pretty useful in those situations where you need to store heterogeneous data, like that in a database record, for example.

Through this tutorial, you’ll dive deep into Python tuples and get a solid understanding of their key features and use cases. This knowledge will allow you to write more efficient and reliable code by taking advantage of tuples.

In this tutorial, you’ll learn how to:

  • Create tuples in Python
  • Access the items in an existing tuple
  • Unpack, return, copy, and concatenate tuples
  • Reverse, sort, and traverse existing tuples
  • Explore other features and common gotchas of tuples

In addition, you’ll explore some alternative tools that you can use to replace tuples and make your code more readable and explicit.

To get the most out of this tutorial, you should have a good understanding of a few Python concepts, including variables, functions, and for loops. Familiarity with other built-in data structures, especially lists, is also a plus.

Getting Started With Python’s tuple Data Type

The built-in tuple data type is probably the most elementary sequence available in Python. Tuples are immutable and can store a fixed number of items. For example, you can use tuples to represent Cartesian coordinates (x, y), RGB colors (red, green, blue), records in a database table (name, age, job), and many other sequences of values.

In all these use cases, the number of elements in the underlying tuple is fixed, and the items are unchangeable. You may find several situations where these two characteristics are desirable. For example, consider the RGB color example:

Python
>>> red = (255, 0, 0)

Once you’ve defined red, then you won’t need to add or change any components. Why? If you change the value of one component, then you won’t have a pure red color anymore, and your variable name will be misleading. If you add a new component, then your color won’t be an RGB color. So, tuples are perfect for representing this type of object.

Some of the most relevant characteristics of tuple objects include the following:

  • Ordered: They contain elements that are sequentially arranged according to their specific insertion order.
  • Lightweight: They consume relatively small amounts of memory compared to other sequences like lists.
  • Indexable through a zero-based index: They allow you to access their elements by integer indices that start from zero.
  • Immutable: They don’t support in-place mutations or changes to their contained elements. They don’t support growing or shrinking operations.
  • Heterogeneous: They can store objects of different data types and domains, including mutable objects.
  • Nestable: They can contain other tuples, so you can have tuples of tuples.
  • Iterable: They support iteration, so you can traverse them using a loop or comprehension while you perform operations with each of their elements.
  • Sliceable: They support slicing operations, meaning that you can extract a series of elements from a tuple.
  • Combinable: They support concatenation operations, so you can combine two or more tuples using the concatenation operators, which creates a new tuple.
  • Hashable: They can work as keys in dictionaries when all the tuple items are immutable.

Tuples are sequences of objects. They’re commonly called containers or collections because a single tuple can contain or collect an arbitrary number of other objects.

In Python, tuples are ordered, which means that they keep their elements in the original insertion order:

Python
>>> record = ("John", 35, "Python Developer")

>>> record
('John', 35, 'Python Developer')

The items in this tuple are objects of different data types representing a record of data from a database table. If you access the tuple object, then you’ll see that the data items keep the same original insertion order. This order remains unchanged during the tuple’s lifetime.

You can access individual objects in a tuple by position, or index. These indices start from zero:

Python
>>> record[0]
'John'
>>> record[1]
35
>>> record[2]
'Python Developer'

Positions are numbered from zero to the length of the tuple minus one. The element at index 0 is the first element in the tuple, the element at index 1 is the second, and so on.

Cool! You’ve had a first glance at tuples. It’s time to dive deeper into all of the above characteristics of tuples and more. To kick things off, you’ll start by learning the different ways to create tuples in Python.

Constructing Tuples in Python

A tuple is a sequence of comma-separated objects. To store objects in a tuple, you need to create the tuple object with all its content at one time. You’ll have a couple of ways to create tuples in Python. For example, you can create tuples using one of the following alternatives:

In the following sections, you’ll learn how to use the tools listed above to create new tuples in your code. You’ll start off with tuple literals.

Creating Tuples Through Literals

Tuple literals are probably the most common way to create tuples in Python. These literals are fairly straightforward. They consist of a comma-separated series of objects.

Here’s the general syntax of a tuple literal:

Python
item_0, item_1, ..., item_n

This syntax creates a tuple of n items by listing the items in a comma-separated sequence. Note that you don’t have to declare the items’ type or the tuple’s size beforehand. Python takes care of this for you.

In most situations, you’ll create tuples as a series of comma-separated values surrounded by a pair of parentheses:

Python
(item_0, item_1, ..., item_n)

The pair of parentheses in this construct isn’t required. However, in most cases, the parentheses improve your code’s readability. So, using the parentheses is a best practice that you’ll see in many codebases out there. In contrast, the commas are required in the tuple literal syntax.

Here are a few examples of creating tuples through literals:

Python
>>> jane = ("Jane Doe", 25, 1.75, "Canada")
>>> point = (2, 7)
>>> pen = (2, "Solid", True)

>>> days = (
...     "Monday",
...     "Tuesday",
...     "Wednesday",