In this tutorial, you’ll learn all you need to know to get started with Python tuples. You’ll learn what tuples are and how they’re different from Python lists. You’ll learn how to create tuples and access data within them using indexing and slicing. You’ll also learn how tuples methods work to allow you to understand their data better.
What are Python Tuples
Python tuples are a collection data type, meaning that, like Python lists, you can use them as containers for other values. There’s no clearly define way to pronounce the term. Sometimes it’s pronounced as “two-ple” and other times as “tuh-ple”.
Let’s take a look at the main attributes of Python tuples:
If you’re familiar with Python lists, tuples may seem incredibly similar. In the next section, you’ll learn some of the key similarities and differences between Python lists and tuples.
Differences Between Python Lists and Tuples
On the surface, Python tuples and lists sound quite similar! And, really, there are a lot of differences. However, there are some notable differences as well! The table below breaks down the similarities and differences between Python tuples and lists:
You can see that, really, the only difference mentioned is that Python lists are mutable, while Python tuples are immutable. This means that once a tuple has been created, a tuple cannot be changed!
Why Use Tuples Over Lists in Python
At this point, you might be wondering, “why even bother with tuples?”. There are two primary reasons for using tuples over lists:
- Immutability: there may be times when you have some values that you simply don’t want to change (especially, accidentally). This is where tuples may are a better choice over lists.
- Memory efficiency: Because Python tuples are immutable, they are significantly more memory-efficient. When a Python list is created, Python doesn’t know how much space to allocate for it in memory. Because of this, some space is reserved. Meanwhile, when a tuple is created, the exact size of that tuple is known!
How To Create a Tuple in Python
A Python tuple is created using regular parentheses, separating items by commas. Let’s take a look at creating your first tuple:
# Your first tuple data = ('welcome', 'to', 'datagy')
Let’s take a look at the type of this tuple,
data, using the built-in
# Checking the type of a tuple print(type(data)) # Returns: <class 'tuple'>
Now, let’s try something else. Let’s create a tuple with a single item:
# Creating a tuple with a single item data = ('datagy')
Let’s check the type of this new object:
# Checking the type of the new tuple print(type(data)) # Returns: <class 'str'>
This is odd! It’s actually the comma that creates the tuple, not the parentheses! It may feel a bit odd, but if you need to create a tuple with only a single item, it needs to have a trailing comma:
# Creating a tuple with a single item data = ('datagy',)
Let’s check the type of this new object:
# Checking the type of the new tuple print(type(data)) # Returns: <class 'tuple'>
What is even more interesting is that the parentheses are actually optional! It really is only the comma that makes the tuple. Writing the code below also produces a tuple:
# Creating a tuple without brackets data = 'datagy', print(type(data)) # Returns: <class 'tuple'>
Now that you know how to create tuples in Python, let’s take a look at how you can access data in tuples.
Accessing Items in Python Tuples
There are a number of easy ways to access items within Tuples. Similar to Python lists, you can access items using indexing and slicing. In the next two sections, you’ll learn how to use both these methods.
Accessing Items with Indexing
Because Python tuples are ordered, you can access individual items using their index position. Python is a 0-based indexed language, meaning that the first item has an index position of 0. Using the index operator
, you can pass in an integer to access that item.
Let’s load a tuple and see how you can access items in that tuple using indexing.
# Accessing items in a tuple with indexing data = ('learn', 'python', 'with', 'datagy') first_item = data print(first_item) # Returns: learn
When you try to access an item beyond the tuples range, an
IndexError is returned. Remember, because Python indices start at 0, the last item will have an index of the length of the tuple minus one. If you tried to access index 4, Python would raise an
# Accessing an item out of range data = ('learn', 'python', 'with', 'datagy') print(data) # Returns: IndexError: tuple index out of range
Python indices can also be accessed using negative indexing. Negative indices begin at the last item with the value of
-1. Let’s see how you can access the last item in the tuple:
# Using negative indexing to access items data = ('learn', 'python', 'with', 'datagy') print(data[-1]) # Returns: datagy
Accessing Items with Slicing
There are often times you need to access multiple items in a Python tuple. You can access a range of items using slicing. Slicing is done using the
 indexing operator, but selecting a range of values using a colon
:. The slice accepts integer values and includes the left value and goes up to (but doesn’t include) the right value. Let’s access the first through second item:
# Slicing a tuple data = ('learn', 'python', 'with', 'datagy') print(data[0:2]) # Returns: ('learn', 'python')
The values on either side of the colon are optional. If either side (or both sides) are omitted, then all values to that end are included. For example, the example above could be rewritten as shown below:
# Slicing a tuple data = ('learn', 'python', 'with', 'datagy') print(data[:2]) # Returns: ('learn', 'python')
Iterating Over Tuples in Python
Because Python tuples are sequence data types, you can iterate over them. For example, you can iterate over a tuple using a simple for loop. Let’s use a for loop to print out every item in the tuple defined above:
# Iterating over a Python tuple data = ('learn', 'python', 'with', 'datagy') for item in data: print(item) # Returns: # learn # python # with # datagy
Iterating over tuples is incredibly straightforward! Similarly, you could build in
if-else conditions to skip over certain items if a condition isn’t met.
Changing Tuples in Python
Python tuples are immutable. This means that they cannot be changed. While with lists, you could append items or modify items using direct assignment, this isn’t possible with tuples. Let’s try this out and see what happens:
# Trying to modify a tuple data = ('learn', 'python', 'with', 'datagy') data = 'hi' # Returns: TypeError: 'tuple' object does not support item assignment
By attempting to modify a tuple’s value, a
TypeError is raised. One thing that’s interesting, however, is that if an item in a tuple is a mutable time, such as a list, a direct assignment works. This is because the reference to the place in memory where that item is stored remains the same!
# Modifying a multable item in a tuple data = ('learning', 'python', 'with', 'datagy', 'is as easy as', [1,2]) data[-1].append(3) print(data) # Returns: ('learning', 'python', 'with', 'datagy', 'is as easy as', [1, 2, 3])
Concatenating and Repeating Tuples in Python
You can also easily concatenate tuples in Python by using the
+ operator. When you do this, a brand new tuple is created. Let’s see how you can concatenate two tuples together:
# Concatenating two tuples first_tuple = (1,2,3) second_tuple = (4,5,6) third_tuple = first_tuple + second_tuple print(third_tuple) # Returns: (1, 2, 3, 4, 5, 6)
Similarly, you can repeat a tuple by using the
* operator in Python.
# Repeating a tuple in Python a_tuple = (1,2,3) a_tuple *= 2 print(a_tuple) # Returns: (1, 2, 3, 1, 2, 3)
Something important to note here is that the code above makes it look like the tuple was mutated. However, the first instance of
a_tuple was destroyed and a new one was created. You can verify this by using the
id() function which returns the space in memory the object is using. Let’s confirm this now:
# Checking the IDs of the tuples a_tuple = (1,2,3) print('First ID: ', id(a_tuple)) a_tuple *= 2 print('Second ID: ',id(a_tuple)) # Returns: # First ID: 140587435474432 # Second ID: 140587435186592
Python Tuple Methods
Python tuples have fewer methods available than mutable types, such as lists. Since you can’t append or modify items in tuples, these methods, of course, don’t exist. However, you can count an element in the tuple and return the index position of an item in a tuple. Let’s see how you can count items using the
# Counting items in a tuple a_tuple = (1,2,3,4,1,2,1) print(a_tuple.count(1)) # Returns: 3
Now, let’s see how you can find the first index of an item in a tuple using the
# Finding the first index of an item in a tuple a_tuple = (1,2,3,4,1,2,1) print("The index position of 2 is: ", a_tuple.index(2)) # Returns: The index position of 2 is: 1
One thing to keep in mind is that if an item doesn’t exist, Python will raise a
It’s time to check your learning! Try and complete the exercises below. If you need a hint or want to check your answer, simply toggle the question to check a solution:
Conclusion and Recap
In this tutorial, you learned everything about the Python tuple, an important container data type. The section below provides a recap of what you learned:
- Tuples are an immutable, iterable, and heterogeneous data type
- Tuples are created using regular parantheses (). A singleton (a tuple with only one item), requires a trailing comma.
- You can access items in a tuple using indexing and slicing
- You can use tuple methods to count items in a tuple and find the first index position of an item
To learn more about related topics, check out the tutorials below: