Python Tuples Tutorial
Similar to Python lists, tuples are another standard data type that allows you to store values in a sequence. They might be useful in situations where you might want to share the data with someone but not allow them to manipulate the data. They can however use the data values, but no change is reflected in the original data shared.
In this tutorial, you will see Python tuples in detail:
Be sure to check out DataCamp's Data Types for Data Science course, where you can consolidate and practice your knowledge of data structures such as lists, dictionaries, sets, and many more! Alternatively, also check out this Python Data Structures Tutorial, where you can learn more about the different data structures that Python uses.
As you already read above, you can use this Python data structure to store a sequence of items that is immutable (or unchangeable) and ordered.
Tuples are initialized with
() brackets rather than
 brackets as with lists.
That means that, to create one, you simply have to do the following:
cake = ('c','a','k','e') print(type(cake))
Remember that the
type() is a built-in function that allows you to check the data type of the parameter passed to it.
Tuples can hold both homogeneous as well as heterogeneous values. However, remember that once you declared those values, you cannot change them:
mixed_type = ('C',0,0,'K','I','E') for i in mixed_type: print(i,":",type(i))
C : <class 'str'> 0 : <class 'int'> 0 : <class 'int'> K : <class 'str'> I : <class 'str'> E : <class 'str'>
# Try to change 0 to 'O' mixed_type = 'O'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-16-dec29c289a95> in <module>() ----> 1 mixed_type = 'O' # Trying to change 0 to 'O' TypeError: 'tuple' object does not support item assignment
You get this last error message because you can not change the values inside a tuple.
Here is another way of creating a tuple:
numbers_tuple = 1,2,3,4,5 print(type(numbers_tuple))
Tuples versus Lists
As you might have noticed, tuples are very similar to lists. In fact, you could say that they are immutable lists which means that once a tuple is created you cannot delete or change the values of the items stored in it. You cannot add new values either. Check this out:
numbers_tuple = (1,2,3,4,5) numbers_list = [1,2,3,4,5] # Append a number to the tuple numbers_tuple.append(6)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-26-e47776d745ce> in <module>() 3 4 # Append a number to the tuple ----> 5 numbers_tuple.append(6) AttributeError: 'tuple' object has no attribute 'append'
This throws an error because you cannot delete from or append to a tuple but you can with a list.
# Append numbers to the list numbers_list.append(6) numbers_list.append(7) numbers_list.append(8) # Remove a number from the list numbers_list.remove(7) print(numbers_list)
[1, 2, 3, 4, 5, 6, 8]
But why would you use tuples if they are immutable?
Well, not only do they provide "read-only" access to the data values but they are also faster than lists. Consider the following pieces of code:
import timeit timeit.timeit('x=(1,2,3,4,5,6,7,8,9)', number=100000)
What does immutable really mean with regards to tuples?
According to the official Python documentation, immutable is 'an object with a fixed value', but 'value' is a rather vague term, the correct term for tuples would be 'id'. 'id' is the identity of the location of an object in memory.
Let's look a little more in-depth:
# Tuple 'n_tuple' with a list as one of its item. n_tuple = (1, 1, [3,4]) #Items with same value have the same id. id(n_tuple) == id(n_tuple)
#Items with different value have different id. id(n_tuple) == id(n_tuple)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-40-3cd258e024ff> in <module>() ----> 1 n_tuple.append(5) AttributeError: 'tuple' object has no attribute 'append'
We cannot append item to a tuple, that is why you get an error above. This is why tuple is termed immutable. But, you can always do this:
(1, 1, [3, 4, 5])
Thus, allowing you to actually mutate the original tuple. How is the tuple still called immutable then?
This is because, the id of the list within the tuple still remains the same even though you appended 5 to it.
To sum up what you have learnt so far:
Some tuples (that contain only immutable objects: strings, etc) are immutable and some other tuples (that contain one or more mutable objects: lists, etc) are mutable. However, this is often a debatable topic with Pythonistas and you will need more background knowledge to understand it completely. This is a more in-depth article for the same. For now, lets just say tuples are immutable in general.
- You can't add elements to a tuple because of their immutable property. There's no
extend()method for tuples,
- You can't remove elements from a tuple, also because of their immutability. Tuples have no
- You can find elements in a tuple since this doesn't change the tuple.
- You can also use the
inoperator to check if an element exists in the tuple.
So, if you're defining a constant set of values and all you're going to do with it is iterate through it, use a tuple instead of a list. It will be faster than working with lists and also safer, as the tuples contain "write-protect" data.
If you want to know more about Python lists, make sure to check out this tutorial!
Common Tuple Operations
Python provides you with a number of ways to manipulate tuples. Let's check out some of the important ones with examples.
The first value in a tuple is indexed 0. Just like with Python lists, you can use the index values in combination with square brackets
 to access items in a tuple:
numbers = (0,1,2,3,4,5) numbers
You can also use negative indexing with tuples:
While indexing is used to obtain individual items, slicing allows you to obtain a subset of items. When you enter a range that you want to extract, it is called range slicing. The general format of range slicing is:
[Start index (included):Stop index (excluded):Increment]
Increment is an optional parameter, and by default the increment is 1.
# Item at index 4 is excluded numbers[1:4]
(1, 2, 3)
# This provides all the items in the tuple numbers[:]
(0, 1, 2, 3, 4, 5)
# Increment = 2 numbers[::2]
(0, 2, 4)
Tip: You can also use the negative increment value to reverse the tuple.
(5, 4, 3, 2, 1, 0)
You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples.
x = (1,2,3,4) y = (5,6,7,8) # Combining two tuples to form a new tuple z = x + y print(z)
(1, 2, 3, 4, 5, 6, 7, 8)
y = [5,6,7,8] z = x + y print(z)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-55-d352c6414a4c> in <module>() 1 y = [5,6,7,8] ----> 2 z = x + y 3 print(z) TypeError: can only concatenate tuple (not "list") to tuple
You can only add or combine same data types. Thus combining a tuple and a list gives you an error.
The multiplication operation simply leads to repetition of the tuple.
x = (1,2,3,4) z = x*2 print(z)
(1, 2, 3, 4, 1, 2, 3, 4)
Unlike Python lists, tuples does not have methods such as
pop() due to its immutable nature. However, there are many other built-in methods to work with tuples:
count() returns the number of occurrences of an item in a tuple.
a = [1,2,3,4,5,5] a.count(5)
len() function, you can returns the length of the tuple:
a = (1,2,3,4,5) print(len(a))
You can use
any() to discover whether any element of a tuple is an iterable. You'll get back
True if this is the case, else it will return
a = (1,) print(any(a))
, in the declaration of the tuple
a above. If you do not specify a comma when initializing a single item in a tuple, Python assumes that you mistakenly added an extra pair of bracket (which is harmless) but then the data type is not a tuple. So remember to add a comma when declaring a single item in a tuple.
Now, back to the
any() function: In a boolean context, the value of an item is irrelevant. An empty tuple is false, any tuple with at least one item is true.
b = () print(any(b))
This function might be helpful when you are calling a tuple somewhere in your program and you want to make sure that the tuple is populated.
tuple() to converts a data type to tuple. For example, in the code chunk below, you convert a Python list to a tuple.
a_list = [1,2,3,4,5] b_tuple = tuple(a_list) print(type(b_tuple))
max() returns the largest element in the tuple, you can use
min() to return the smallest element of the tuple. Consider the following example:
You can also use this with tuples containing string data type.
# The string 'Apple' is automatically converted into a sequence of characters. a = ('Apple') print(max(a))
With this function, you return the total sum of the items in a tuple. This can only be used with numerical values.
To return a tuple with the elements in an sorted order, use
sorted(), just like in the following example:
a = (6,7,4,2,1,5,3) sorted(a)
[1, 2, 3, 4, 5, 6, 7]
It is worth noting that the return type is a list and not a tuple. The sequence in the original tuple 'a' is not changed and the data type of 'a' still remains tuple.
Bonus: Assigning Multiple Values
Something cool that you can do with tuples is to use them to assign multiple values at once. Check this out:
a = (1,2,3) (one,two,three) = a print(one)
a is a tuple of three elements and
(one,two,three) is a tuple of three variables. Assigning
a tuple assigns each of the values of
a to each of the variables: one, two and three, in order. This can be handy when you have to assign a range of values to a sequence stored in a tuple.
You have made it to the end of this tuple tutorial! Along the road, you learned more about what Python tuples are, how you can initialize them, what the most common operations are that you can do with them to manipulate them and what the most common methods are so that you can get more insights from these Python data structures. As a bonus, you learned that you can also assign multiple values to tuples at once.