March 28, 2022

Python Tuples: A Step-by-Step Tutorial (with 14 Code Examples)

When working with data collections, we occasionally encounter situations where we want to ensure it's impossible to change the sequence of objects after creation.

For instance, when reading data from a database in Python, we can represent each table record as an ordered and unchangeable sequence of objects since we don't need to alter the sequence later. Python has a built-in sequence data type to store data in an unchangeable object, called a tuple.

After you finish this Python tutorial, you'll know the following:

  • How to work with tuples in Python
  • The difference between tuples and lists in Python
  • The basic uses of tuples

In this tutorial, we assume you know the fundamentals of Python, including variables, data types, and basic structures. If you're not familiar with these or would like to review, you might like to try our Python Basics for Data Analysis – Dataquest.

Let's dive in.

What Is a Python Tuple?

A tuple represents a sequence of any objects separated by commas and enclosed in parentheses. A tuple is an immutable object, which means it cannot be changed, and we use it to represent fixed collections of items.

Let's take a look at some examples of Python tuples:

  • () — an empty tuple
  • (1.0, 9.9, 10) — a tuple containing three numeric objects
  • ('Casey', 'Darin', 'Bella', 'Mehdi') — a tuple containing four string objects
  • ('10', 101, True) — a tuple containing a string, an integer, and a Boolean object

Also, other objects like lists and tuples can comprise a tuple, like this:

a_tuple = (0, [1, 2, 3], (4, 5, 6), 7.0)

The code above creates a tuple containing an integer, a list, a tuple, and a float number. The following code returns the entire tuple and its data type.

print(a_tuple)
print(type(a_tuple))
(0, [1, 2, 3], (4, 5, 6), 7.0)

However, ('A') is not a tuple. Let’s look at its data type:

print(type(('A')))

So, how can we declare a single-value tuple? The answer is easy. We need to add an extra comma just before the closing parenthesis, like this:
('A',)
The trailing comma means that the parentheses are holding a single-value tuple, not to increase the precedence of a mathematical operation.

Indexing and Slicing a Tuple

As mentioned earlier, because a tuple is a sequence of objects, we can access these objects through indexing. As with strings, the index of the first element is 0, the second element is 1, and so on. Let’s try indexing a tuple:

print('The first element:', a_tuple[0])
print('The last element:', a_tuple[-1])
print('The data type of the second element:', type(a_tuple[1]))
The first element: 0
The last element: 7.0
The data type of the second element: 

In the code above, the first and second statements return the values of the tuple's first and last elements. The last statement prints out the data type of the second element of the tuple, which is a list object.

Furthermore, the following piece of code shows how to retrieve the second element of the inner tuple, at index 2.

print(a_tuple[2][1])
5

This means that we can access an element stored in an inner tuple (a tuple stored inside another tuple) by doing a series of indexing operations.

Slicing a tuple is as simple as slicing a Python string or a list with the same rules. To get a range of elements within a tuple, we can specify a range of indices to retrieve by selecting where to start (inclusive) and end (exclusive) the range.

Let’s take a look at some examples:

num_tuple = 2, 4, 5, 7, 8, 10
print(num_tuple[:3])
print(num_tuple[4:])
print(num_tuple[-3:])
print(num_tuple[2:5])
(2, 4, 5)
(8, 10)
(7, 8, 10)
(5, 7, 8)

The first line of the code declares a tuple of integer values. Although it’s unusual, it’s another way to declare a tuple by providing a sequence of objects separated by commas without enclosing them in parentheses. The subsequent statements print out different slices of the tuple, as shown.


NOTE

If you’re not familiar with indexing and slicing a sequence object in Python or would like to review, there is a good tutorial on the Dataquest blog at Tutorial: Demystifying Python Lists.


To concatenate two or more tuples, we can use + sign as with strings. For example, the following code concatenates two tuples:

tuple_1 = (1, 2)
tuple_2 = (3, 4)
print(tuple_1 + tuple_2)
(1, 2, 3, 4)

Moreover, multiplying a tuple by an integer produces a tuple containing the original tuple repeated that many times. Let’s try it:

my_tuple = (1, 7, 9, 8)
print(my_tuple * 2)
(1, 7, 9, 8, 1, 7, 9, 8)

Zipping Tuples

The zip() method takes multiple sequence objects and returns an iterable object by matching their elements. To learn more about zipping tuples, consider the following example.

Let's assume that we have three different tuples containing the personal details of four customers. We want to create a single tuple that holds the corresponding data for each customer, including their first name, last name, and age, in the form of separate tuples:

first_names = ('Simon', 'Sarah', 'Mehdi', 'Fatime')
last_names = ('Sinek', 'Smith', 'Lotfinejad', 'Lopes')
ages = (49, 55, 39, 33)
zipped = zip(first_names, last_names,ages)
print(zipped)

We declare the first_name, last_name, and ages tuples in the code above. The zip() method takes the three tuples and returns a zip object, which is an iterator. To consume the iterator object, we need to convert it to either a list or a tuple, like this:

customers = tuple(zipped)
print(customers)
(('Simon', 'Sinek', 49), ('Sarah', 'Smith', 55), ('Mehdi', 'Lotfinejad', 39), ('Fatime', 'Lopes', 33))

The customers tuple consists of four tuple objects, each of which belongs to a customer.

Unpacking Tuples

Unpacking a tuple allows us to extract the tuple elements and assign them to named variables. Let’s try it:

first_name, last_name, age = customers[2]
print(first_name, last_name, ',', age, 'years old')
Mehdi Lotfinejad , 39 years old

The code above retrieves the tuple elements stored at index 2 of the customers tuple and assigns them to the first_name, last_name, and age variables.

Difference Between Tuples and Lists in Python

Besides the intuitive difference between tuples and lists, as mentioned before, tuples are immutable, so unlike lists, tuples cannot be modified. However, some technical differences make tuples an undeniable asset in Python programming.

The first difference that makes lists more preferable iterable objects than tuples is that a list object provides more methods. But the extra functionality comes at a price. Let’s first look at the size of the occupied memory of each object in the code below, then discuss why tuples are the better choice in some situations.

import sys
a_list = ['abc', 'xyz', 123, 231, 13.31, 0.1312]
a_tuple = ('abc', 'xyz', 123, 231, 13.31, 0.1312)
print('The list size:', sys.getsizeof(a_list), 'bytes')
print('The tuple size:', sys.getsizeof(a_tuple), 'bytes')
The list size: 104 Bytes
The tuple size: 88 Bytes

We can see that a list object occupies more memory than a tuple object. The significance of occupying less memory becomes more apparent when we work with big data, which means immutability makes significant optimization when working with a large amount of data.
In addition to occupying less memory, processing tuple objects is much faster than lists, especially when dealing with millions and millions of sequence objects.

Usage of Python Tuples

This section will discuss two exciting ways of using tuples in practice. Let’s explore them.

Tuple Element Swapping

We can use tuples to swap the values associated with variables only if the variables are tuple elements. Let’s try it out:

x = 19
y = 91
print('Before swapping:')
print(f'x = {x}, y = {y}')
(x, y) = (y, x)
print('After swapping:')
print(f'x = {x}, y = {y}')
Before swapping:
x = 19, y = 91
After swapping:
x = 91, y = 19

The value of y is assigned to the x variable, and the x value is simultaneously assigned to the y. It’s a more Pythonic way to swap values.

Returning More Than One Value from a Function

Functions can only return a single value. However, we can use a tuple and put as many values as we need inside it, then return the tuple object as the function’s return value. Let’s see how we can use a tuple to return multiple values from a function in the following code:

def sum_and_avg(x, y, z):
    s = x + y + z
    a = s/3
    return(s, a) 
(S, A) = sum_and_avg(3, 8, 5)
print('Sum =', S)
print('Avg =', A)
Sum = 16
Avg = 5.333333333333333

The sum_and_avg() function calculates the sum and average of three numeric values. The function returns s and a, which are the two values that it calculates, in the context of the tuple object. In fact, the function only returns a single value, which is a tuple object containing multiple values. We also used the tuple unpacking technique to extract the values in the returned tuple object, then print them out.

Conclusion

This tutorial covered how to create tuple objects, as well as many aspects of Python tuples, such as indexing, slicing, zipping, unpacking, etc. We also discussed the difference between tuples and lists. Using Python tuples properly will definitely make our code more efficient and robust.

Dataquest

About the author

Dataquest

Dataquest teaches through challenging exercises and projects instead of video lectures. It's the most effective way to learn the skills you need to build your data career.