Tuple is a built-in data type in Python that is used to store a collection of data. It is similar to a list but is slightly faster.
However, its limitations make lists more desirable in some situations. In this article, I will explain everything you need to know to get started using tuples.
What Is a Tuple?
As mentioned earlier, a tuple is one of the built-in data types in Python used to store collections of data. It is similar to a Python list in that it stores data in an iterable, array-like format. Unlike a list, however, a tuple is immutable. That is, once created, its values cannot be changed.
Additional elements cannot be added, and existing elements cannot be removed. A tuple, therefore, is ideal when storing data that does not change. It may even be a collection of data of different types. In the next section, we will discuss the different ways of creating tuples in Python.
How to Create a Tuple in Python?
There are at least three ways to create tuples in Python. In this section, we will cover three of the most common methods you will likely use and see when reading code from others.
To run the following code examples, you will need to have Python installed. If you do not have Python already installed, here’s a helpful guide to installing Python. Alternatively, you can run your code in an online Python runtime like Google Colab.
#1. Using the Tuple Literal (Parentheses)
The most common way to see tuples defined in Python is by placing a collection of values between parentheses. These values are separated by commas. The following example illustrates this method:
# Creates a tuple by placing values between parentheses values = (1, 2, 3) # Printing out the tuple to the screen print(values) # Printing out the type of values variable print(type(values))
Running this code will produce the following:
As you can see from the output, the tuple holds the values we initialized it with. It is also of type
When you create tuples in Python, parentheses are not necessary. Therefore this
values = 1, 2, 3 is equally as valid as this
values = (1, 2, 3). It is, however, recommended that you use parentheses to make your code more understandable.
Creating tuples with one element in Python is a little bit tricky. Instead of just placing one element between parentheses, you also need to add a trailing comma. Here is an example to illustrate:
# Without trailing comma, this won't create a tuple not_a_tuple = (1) # With trailing comma, this will create a tuple a_tuple = (1,) # Printing not_a_tuple print(not_a_tuple) # Printing not_a_tuple's data type print(type(not_a_tuple)) # Printing a_tuple print(a_tuple) # Printing a_tuple's data type print(type(a_tuple))
Running the code above, you will see that
not_a_tuple becomes an
int of value 1. This is important to keep in mind when creating tuples.
#2. Using the Constructor Function
The second method for creating tuples in Python uses the tuple constructor function. In this method, you call the function, passing an iterable object like a list as an argument. This will be converted to a tuple. Here is an example:
# Creating tuple from a list of values values = tuple([1, 2, 3]) # Printing out the values print(values) # Printing out the data type of the values identifier print(type(values))
As you can see, using the function achieves the same result as using the literal. However, the function enables you to create a tuple based on a dynamic value, such as a list whose values are only known at runtime. With the first method, you would have to know the values or identifiers that make up your tuple while writing the code.
#3. Creating an Empty Tuple
As you work with tuples in your code, you may need to create empty tuples. Empty tuples are created as you would expect. You can use either the tuple constructor or the literal to when creating them. Here is an example demonstrating how to use either method:
# Using the tuple literal empty_tuple_1 = () # Using the constructor empty_tuple_2 = tuple()
Empty tuples are useful when representing an empty set of results. Consider the following function:
def create_range(start, end): return tuple(range(start, end))
This function creates a tuple with values from the start, up to the end value you pass in. If you wanted to iterate over the results of the function you would use something like this:
my_values = create_range(0, 5) for value in my_values: pass
If you provided 5 and 5 to the create_range function, the result would be an empty tuple. And if you tried to iterate over it, you would just have zero iterations, and your code would proceed as normal.
On the other hand, if there were no empty tuples, and instead you got the None value, then trying to iterate over it would throw an error. To prevent crashing the program, you would have to implement a test for the edge case that the create_range function returns None or any other value that represents an empty tuple.
This would lead to messy code. Ideally, you would want to avoid special cases as much as possible. This means the return value of all functions should have an identical interface so that your code works in the general case as much as possible. In this case, this means returning a tuple all the time, although, at times, it will be empty.
How to Access Elements
There are two ways to access a tuple’s elements in Python. The first method is by index, and the second is by destructuring the elements. First, we will examine how to access elements by index.
Accessing Elements by Index
Accessing elements by the index is similar to how you would access list elements by index. This is done using square-bracket notation. Tuples use a zero-based indexing system meaning the first element is index 0, and the one after is index 1 until the last element.
The example below demonstrates how to access elements by index:
# Creating a tuple values = (1, 2, 3, 4) # Accessing the first element first_element = values # Accessing the fourth element(index 3) fourth_element = values
You can also use negative indexing. The element with index -1 is the last element, and the element with index -2 is the second from the last element.
# Creating the tuple values = (1, 2, 3, 4) # Accessing the last element last_element = values[-1] # Accessing the second from last element second_from_last_element = values[-2]
In addition, you can also access subcollections of elements from a tuple by slicing it. This is similar to how you would slice a list. The notation is as follows
<tuple>[<start>: <end>: <skip>]. The following example demonstrates slicing:
# Creating the tuple values = (1, 2, 3, 4, 5, 6, 7) # Getting the first three elements values[1: 3] # Getting every other element values[::2]
Iterating Over Elements
A tuple is an iterable object in Python. Therefore you can iterate over its elements using a for loop, as shown in the following example:
values = (1, 2, 3, 4) for value in values: print(value)
This method of accessing elements is ideal when you want to access all the elements in the tuple.
Accessing Elements by Destructuring
To explain destructuring, consider the following scenario where we are trying to get the different elements in a tuple.
# Creating the tuple to record a user's information person_record = (1, 'John Doe', 'email@example.com') # Accessing the different elements in the tuple to use in our code id = person_record name = person_record email = person_record
Python allows us to use a more convenient method to access the values, as illustrated below:
# Creating the tuple to record a user's information person_record = (1, 'John Doe', 'firstname.lastname@example.org') id, name, email = person_record
This is called destructuring. That is the first variable,
id in this case, will be assigned the first value in the tuple and the second variable to the second element. This goes on to the end of the tuple. The above example is equivalent to this:
id, name, email = (1, 'John Doe', 'email@example.com')
In this case, instead of storing the tuple in a variable, we are immediately destructuring it. When you combine this with the knowledge that you do not need to use parentheses when creating tuples, then you can write the code like this.
id, name, email = 1, 'John Doe', 'firstname.lastname@example.org'
At the end of all this, you will have id, name, and email variables with the values 1, ‘John Doe’ and ‘email@example.com’. This is a convenient and succinct way of creating variables in Python that you will see in production code. It helps to know that at the heart of this elegant syntax is the concept of tuples.
Differences Between Tuple and List
While the two are similar, some key differences make each one more suited for a particular use case. Understanding these differences will help you decide on the best data type to use and write better and more efficient code.
|Memory Storage||Stored in contiguous memory||Store in different parts of memory|
|Mutability||Immutable (cannot be changed)||Mutable (can be changed)|
|Speed||Access is faster||Access is slower|
|Data type||Usually stores data of different types||Usually stores data of the same type|
|Use cases||Usually used to store a collection of similar values, such as marks.||Usually used to store a collection of similar values such as marks.|
Advantages of a Tuple
#1. It Is Faster
Because of how the values of a tuple are stored in contiguous memory, accessing the values is faster compared to a list. However, because once created, they cannot be changed, tuples are not always the best data structure to use to store collections of values.
Their ideal use case is storing lots of data in memory that does not change but will be accessed several times during program execution. In this case, your program will benefit immensely from the performance boost of tuples.
#2. Return Multiple Values
You can use tuples to return multiple values from a function and destructuring the result. For example:
from random import randint def create_two_numbers(): first_num = randint(0, 9) second_num = randint(0, 9) return first_num, second_num first_num, second_num = create_two_numbers()
In this example, we have a function that creates two random numbers and returns them both in a tuple. The
return first_num, second_num statement is equivalent to writing
return (first_num, second_num). This is because parentheses are optional when creating tuples. To access the result, we are destructuring it.
#3. Values are Write-Protected
Tuples are immutable once created. They are, therefore, ideal for storing data in memory that does not change during program execution. They ensure that you do not accidentally overwrite the data somewhere else in your code.
#4. Store Multiple Data Types
Tuples allow you to store values of multiple data types. This allows you to create records of data, such as storing a user’s details in a tuple. You can also store more complicated items such as functions, dictionaries, other tuples, and even lists.
Common Tuple Methods
The tuple object contains the count method, which counts the number of times an element occurs. For example:
# Creating a tuple with several numbers values = (1, 2, 3, 4, 5, 4, 4, 6) # Counting the number of fours n_fours = values.count(4) # Prining out the number of fours print(n_fours)
From this example, we can see that the number 4 occurs exactly three times in our tuple.
The index method can be used to find the index of the first occurrence of a value in a tuple. If the value does not exist, an
ValueError exception will be thrown. Here is some code to illustrate how the
index method works:
# Creating a tuple with several numbers values = (1, 2, 3, 4, 5, 4, 4, 6) # Search for index of 4 index_of_four = values.index(4) print("Index of four:", index_of_four) # Search for index of 9 index_of_nine = values.index(9) print("Index of nine:", index_of_nine)
And when we run the code above, this is the output:
In this case, the index of 4 is 3, and the code ran without issues. But when it came to finding the index of 9, the program raised an exception. It is important to handle such exceptions when you are writing Python programs that use the index method.
Like all iterable objects in Python, tuples have a length property that you can access when you pass in the tuple as an argument to the
# Creating a tuple values = (1, 2, 3, 4) # Getting the length length = len(values) # Print the output print(length)
This is the result of running the above code.
#4. min() and max()
The min and max methods work by looping through each element in an iterable and comparing if it is greater or less than the one before it. In the end,
max will return the largest element in the iterable while
min returns the smallest.
With numbers, the operation is obvious. With strings, Python will use alphabetic order. The smallest word, returned by
min, is the first word if the strings were written in alphabetic order. While the largest word is the last word. If the iterable contains a mix of different data types, then the operations will both fail because Python does not know how to compare different data types.
Here is a code example:
# Creating tuple with values values = (1, 2, 3, 4, 5) # Getting the largest value largest = max(values) # Getting the smallest value smallest = min(values) # Output the results print(largest) print(smallest)
The sorted function in Python takes in an iterable object and returns a list of the elements sorted. You can call the sorted function, pass in a tuple as an argument, and get the elements of the tuple sorted in a list. To convert the sorted list to a tuple, you can use the constructor function. Here’s an example:
# Creating a tuple with values in random order values = (1, 5, 3, 3, 2, 4) # Using sorted to sort the values into a list sorted_list = sorted(values) # Converting the list into a tuple sorted_tuple = tuple(sorted_list) # Printing the output print(sorted_tuple)
#6. Adding and Multiplying Tuples
The addition operation on two tuples simply concatenates them together. The multiplication operation repeats the elements of a tuple as many times as the value you multiplied with. Here is an example to illustrate the two examples.
# Create a tuple with some values values = (1, 2, 3, 4, 5) # Create a new tuple using addition added = values + values # Create a new tuple using multiplication multiplied = values * 2 print("values + values =", added) print("values * 2 =", multiplied)
In this article, you learned that:
- Tuples are list-like objects used for storing collections of values.
- Unlike lists, they are immutable.
- They are faster and more efficient than lists.
- They can be constructed using parentheses and separating the values with commas.
- They can also be constructed using the
- You can access individual values using a zero-based index system.
- You can also destructure values from the tuple.
- You can also iterate over values using a for-loop.
- The different methods that you can use with a tuple.
Next, you may want to check out more Python content, such as Python List Methods and Python Dictionary Methods.