Summary: In this tutorial, we will learn what the tuple is in Python, how can we create it, what operations we can perform on it, and when we should use it in our Python program.
Introduction to Tuple in Python
The tuple is one of the data structures that comes built-in with Python. It is used to store multiple objects of any data type in an ordered manner.
The following data structure is an example of a tuple in Python:
>>> t = (1, 1 , 2, "Python") >>> print(t) (1, 1 , 2, "Python")
As you see, the tuple data structure maintains the order of the objects in which they have been defined.
The tuple is very much similar to a Python list. The items stored in it are ordered and indexed.
We can easily fetch the items from a tuple using the indexing operator (i.e,
) in Python.
>>> t = (1, 1 , 2, "Python") >>> print(t) Python
However, unlike the list, the tuple is immutable. Once it has been defined, its items cannot be modified.
>>> t = (1, 2, 5, 10) >>> t = 6 TypeError: 'tuple' object does not support item assignment
Because of its immutability nature, we cannot even add or remove any items in the tuple.
This is the reason why tuple doesn’t support append() or extend() method like a list.
How to create a tuple in Python?
There are two ways in which we can define a tuple in Python:
- Using parenthesis i.e.,
When we enclose any elements in the parenthesis (i.e.,
()), they get defined in a tuple.
>>> names = ('Jhon Don', 'Jack Rose', 'AK') >>> print(type(names)) <class 'tuple'>
This is the easiest way to create a tuple from any data type in Python. However, we should be careful when defining a tuple from a single element because Python considers the single element inside a parenthesis (e.g.,
(5)) as an expression and as a result, evaluates it.
For example, in the following code, although we are trying to create a tuple, Python is defining an integer variable instead:
>>> t = (5) >>> print(type(5)) <class 'int'>
In such cases, we need to include a trailing comma (,) inside the parathesis, to instruct Python that we defining a tuple.
>>> t = (5, ) >>> print(type(5)) <class 'tuple'>
This ambiguity only happens in a singleton tuple (a tuple with only one element), not in an empty, or a tuple with more than one element.
Alternatively, we can use the
tuple() constructor to construct a tuple but, it only accepts iterables such as string, list, set, etc, as the parameter.
>>> t = tuple("Programmer") >>> print(t) ('P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r')
Python Tuple Operations
There are various operations such as indexing, slicing, concatenation, multiplication, etc, which we can operate on a tuple in Python. Let’s see each of them one by one.
The tuple associates each of its elements with a corresponding number called index, using which we can easily access its elements.
The index starts with 0 from the first element and increases with the position of the elements.
By using the indexing operator (
) and the index value, we can instantly access items at any position in the tuple.
>>> t = ("Python", "C++", "Java") >>> print(t) C++
If we try to access any elements at an index that is beyond the limit of the tuple, we will get an out-of-range error.
>>> t = (4, 5) >>> print(t) IndexError: tuple index out of range
Negative Indexing of Tuples
Since Python supports negative indexing, we can also use negative index values to get items relative to the end of the tuple.
In negative indexing, the indexing starts from the last item with a value of -1 and subsequently decreases as it approaches the first item.
>>> t = ("Python", "C++", "Java") >>> print(t[-1]) Java
Slicing a data structure means extracting a subset of the data structure based on certain parameters such as index values.
In Python, we can easily slice a tuple using the indexing operator (
) and a colon (
If we want to get all items of the tuple after the index
x (including the value at index
x), we should write the tuple as
>>> t = (1, 2, 3, 4, 5) >>> print(t[2:]) (3, 4, 5)
Similarly, to get all items before a particular index, for example
y, we should write the tuple as
t[:y]. In this case, the Python doesn’t include the item at the index
>>> t = (1, 2, 3, 4, 5) >>> print(t[:2]) (1, 2)
If we need to slice the tuple based on two index values, we should write the tuple as
t[x:y], where t, x, and y are the name of the tuple, start index and end index respectively.
>>> t = ('a', 'b', 'c', 'd', 'e', 'f') >>> print(t[1:4]) ('b', 'c', 'd')
Another expression that we can use to slice a tuple is
t[x:y:z]. Here, z is the step value that determines the gap between two index numbers of the subset.
>>> t = ('a', 'b', 'c', 'd', 'e', 'f') >>> print(t[1:4:2]) ('b', 'd')
If we do not provide the values for
[x:y:z], then we get the whole tuple with the index difference of
>>> t = ('a', 'b', 'c', 'd', 'e', 'f') >>> print(t[::2]) ('a', 'c', 'e')
Python allows using arithmetic operators like
* on the tuple data structure.
On using the + operator on two tuples, the tuples get concatenated into one.
>>> t1 = (1, 2, 3) >>> t2 = ('a', 'b', 'c') >>> t3 = t1 + t2 >>> print(t3) (1, 2, 3, 'a', 'b', 'c')
* operator when used with an integer on a tuple, the tuple’s items replicate by the same number of times.
>>> t = ("ML", "AI", "are", "Awesome") >>> print(t*2) ('ML', 'AI', 'are', 'Awesome', 'ML', 'AI', 'are', 'Awesome')
+ operator, we cannot use
* operator on two tuples (i.e., the
tuple*tuple operation is not allowed in Python).
Length of the Tuple
len() function, we can easily find the number of items available in a tuple data structure.
>>> t = (1, "one") >>> len(t) 2
>>> t = ("Jon", "AK", "Harry", "Ron") >>> for x in t: ... print(x, end=' ') ... Jon AK Harry Ron
Why to Use Tuples in Python?
The tuple data structure in Python is immutable. We cannot add, remove or extend once it is defined.
Because of its immutability, it is faster than the list (which is dynamic).
Hence, when we don’t have the requirement of modifying the data structure and the execution time of the program is important, we should choose a tuple over a list.
Some of the inbuilt methods that we can use on tuples in Python are:
count(x)– returns the count of how many ‘x’ are present in tuple.
index(x)– returns the index of ‘x’.
min(tuple)– returns minimum value item in tuple.
max(tuple)– returns maximum value item in the tuple.
len(tuple)– length of the tuple.
cmp(tuple1, tuple2)– compares length of two tuples.
The tuple is a data structure in Python that is immutable, indexed, ordered, and un-dynamic.
A tuple can store objects of any data type (also duplicates) and allows operations such as slicing, indexing, concatenating, multiplying, etc.