In this tutorial, we are going to talk about Python Tuple and Nested Tuple with example. We will also go through different operations present in tuple.
Getting Started
In Python, Tuples are collections, built-in data structure used to store different data types. Tuples items are enclosed in parenthesis i.e. () and are separated by commas. They have the particularity of being ordered and immutable.
In a simpler way, Tuples are ordered and immutable sequences of elements of different data types such as integer, float, string, list or even tuple.
Create Tuple in Python
There are multiple ways to create Tuple in Python. They are –
-
Create Tuple Using Parenthesis
In python, several means are used to create tuple and parenthesis i.e. () are one of them. Parenthesis can be used to create tuple as shown below. It can store any data type.
Example 1
my_tuple1 = (1, 2, 3, 4, 5)
Here,
() created a tuple having elements 1, 2, 3, 4 and 5 and are stored in my_tuple1. All elements are integers in tuple my_tuple1.Example 2
my_tuple2 = ("mangoes", 85, "oranges", 90.2)
Tuple object my_tuple2 is used to store items of different data type. Items “mangoes” and “oranges” belong to string data type and the items 85, 90.2 belong to integer and float data type respectively.
Example 3
my_tuple3 = (["sport", "fruits"], ["foods", "carbohydrate"], [90, 100])
Tuple object named my_tuple3 and its items are [“sport”, “fruits”], [“foods”, “carbohydrate”] and [90, 100]. All these items present in my_tuple3 are list object. Therefore, my_tuple3 is used here to store list data type.
Example 4
my_tuple4 = (1, 2, 3, 4, 5, (40, 60))
Tuple object named my_tuple4 contains integer object and tuple object as items. Integers present in my_tuple4 are 1, 2, 3, 4, 5 and tuple object is (40, 60).
As we have seen, tuple is a data structure and it can store integer, float, string, dictionary, set and even tuple.
In Python, parenthesis can also be used to create an empty tuple :
my_tuple = ()
Here,
my_tuple is an empty tuple. -
Create Tuple Using tuple constructor
Apart from parenthesis, tuple() constructor is also used to create a tuple object in Python. The following Python code is an example.
my_tuple = tuple("123456789") print(my_tuple)
Output:
('1', '2', '3', '4', '5', '6', '7', '8', '9')
In these Python codes we are creating a tuple object by using the constructor tuple(). tuple() is an internal Python constructor that accepts an iterable as parameter and creates a new tuple object in Python.
Constructor tuple() took as parameter “123456789” which is integers sequence. Then, it will return an enclosed parenthesis containing each occurrence of the iterable(parameter). Each occurrence is separated from another by comma. Hence, output of above code are respectively (‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’).
Example 2
my_tuple = tuple("tutorialwing") print(my_tuple)
Output:
so('t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'w', 'i', 'n', 'g')
Here, constructor tuple() accepted “tutorialwing” as parameter which is string sequence. After parameters are given to the constructor tuple(), it will return an enclosed parenthesis containing each occurrence of the iterable(parameter). Each occurrence is separated from another by comma. So, the output is (‘t’, ‘u’, ‘t’, ‘o’, ‘r’, ‘i’, ‘a’, ‘l’, ‘w’, ‘i’, ‘n’, ‘g’).
Note : The constructor tuple() can also be used to create an empty tuple in Python. For example,
my_tuple = tuple()
Here,
my_tuple is an empty tuple using tuple constructor. -
Create Tuple Using tuple Packing
Tuple packing in Python is another way used to create a tuple object in Python. Creating tuple packing consists to assign or to store multiple value into a variable. Each value must be separated from another by comma. The following Python code is an example.
my_tuple = "mango", "orange", "banana" print(my_tuple)
Output:
('mango', 'orange', 'banana')
In this code we have created a tuple named my_tuple by assigning “mango”, “orange”, “banana” to the tuple name. The output is a tuple containing different values we have assigned.
Creating Tuple With Only One Element
We said above that we can create an empty tuple by using parenthesis or the tuple constructor. In the same way we can create a tuple with a single element by using parenthesis as shown below.
my_tuple = ("mango", )
Note : When a tuple contains only one item or a single item, we must follow this item by comma. Otherwise it will not be treated as tuple object but as simple integer if item is an integer. By default, sequences without parenthesis are treated as tuple.
Get Length of Tuple in Python
len() is an internal function to Python. It is used to get the number of elements or items present in containers. Thus, to get a tuple length in Python we are going to use len() function as shown below.
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(len(my_tuple))
Output:
5
In above code, we apply the len() function to variable my_tuple and the output equals to 5 because total number of items present in my_tuple is equals to 5.
Get Type of Tuple in Python
In Python, when we want to get type of a variable or an iterable we use type() function.
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(type(my_tuple))
Output:
class 'tuple'
In above code, we are going to get the type of variable my_tuple by using the Python internal function – type().
Access Elements in Tuple
There are multiple ways to access elements of tuple in python. They are –
-
Access Tuple Elements by Indexing
In Python, each item present in a tuple has its corresponding position. So, to access an item present in a tuple, we will use its corresponding position. Clearly if we want to access an item present in a tuple, we can use the tuple name followed by its position enclosed in square brackets. For example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[2])
Output:
avocado
In above Python code, we want to access to the third item of tuple object named my_tuple. The position of the third item present in my_tuple will be equal to 2, as index counting starts from 0. Hence, output is avocado because it is present at 3rd position from left side.
We have seen that an item can be accessed in a tuple by using its corresponding position. Now, what will be happen if position didn’t have a corresponding item in a tuple ?
Answer is –
When there is no item corresponding to given position in tuple, code raises an IndexError. For example,my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[5])
Output:
IndexError: tuple index out of range
In above code, we got an IndexError because there is no item in the variable my_tuple that equals to position 5.
-
Access Tuple Elements by Negative Indexing
In Python, negative indexing method is almost the similar as indexing method.
The difference is –
In indexing method, counting position starts from 0 from the left side. But, in negative indexing, counting position starts from -1 from the right side.So, the last item in the tuple corresponds to position -1. Last but second item corresponds to position -2 and so on. Check below image –
Let’s take an example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[-2])
Output:
orange
In above code, we’re trying to get the item before the last in the tuple by using negative indexing. The position counting will start by -1 from the right side and the item before the last corresponds to position -2. Item corresponding to position -2 in my_tuple is orange. So, output is orange.
Note : As we said above an IndexError will be raised when the given position doesn’t has a corresponding value in the tuple. For example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[-6])
Output:
IndexError: tuple index out of range
Position -6 doesn’t have corresponding item in the tuple.
-
Access Tuple Elements by Slicing
As name depicts, slicing means cut into slices. It means iterable will be cut into different section.
In the same way, Tuple Slicing means cut the tuple into different slices.Using this technic, we can access elements of tuple in python.
To slice an iterable, we use the iterable name followed by square brackets containing two colons and the positions of items we want. Brackets before the first colon represents starting index. It means that we will get items of the iterable by starting from this index. After the first colon, we have ending index. It means that we will get items of the iterable before that index. So, item corresponding to end index is not included to the slicing. After the second colon, we have the step, by default equals to 1.
For example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[ : : ])
Output:
("mango", "guava", "avocado", "orange", "pineapple")
In above code, we are slicing a tuple object named my_tuple. Notice that there are two colons between parenthesis. Since starting index and end index are not specified, it will get all items present in the iterable object. That’s why we got all items contained in my_tuple as output.
Only End Index is Specified
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[ : 3 :])
Output:
('mango', 'guava', 'avocado')
In above program, end index is specified which is equal to 3. It means that we will get all items in my_tuple from 0th index to 2nd index. Hence, output is (‘mango’, ‘guava’, ‘avocado’). If index is not specified, it equals to 0.
Start and End Indexes are Specified
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[ 1 : 2 : ])
Output:
('guava',)
Here, starting and end indexes are specified that are 1 and 2 respectively. It means that we will get all items in my_tuple by starting from position 1 and end to position 1 because the end index in the bracket is 2. As we discussed above, end position is the end index minus 1. So, we will get (‘guava’,) as output.
Add Item in a Tuple in Python
In Python, when we want to add an element or an item to an existing tuple, we use the operator of addition +. The operator of addition adds the new item at the end of given tuple. For example,
my_tuple = ("mango", "guava", "avocado", "orange") my_tuple + ("pineapple", ) print(my_tuple)
Output:
('mango', 'guava', 'avocado', 'orange', 'pineapple')
In above example, we are adding new item ‘pineapple’ to the tuple object named my_tuple. New item must also be a tuple. That’s the reason why we created a tuple object with ‘pineapple’ as single item.
Remove Item in Tuple in Python
After creating a tuple object we cannot remove any of its items because tuples are immutable. It means that we can neither modify nor delete items of a created tuple. We will get a TypeError if we try to do so.
There is no method or proper way to remove tuple item in Python. For example,
my_tuple = ("mango", "guava", "avocado", "orange") del my_tuple[1] print(my_tuple)
Output:
TypeError: 'tuple' object doesn't support item deletion
As discussed, item cannot be deleted in a tuple.
Update Item in Tuple in Python
Tuples are immutable. This means that we cannot change or modify any of tuple item. So, we get a TypeError as shown below if we try.
my_tuple = ("mango", "guava", "avocado", "orange") my_tuple[1] = "apple" print(my_tuple)
Output:
TypeError: 'tuple' object does not support item assignment
This output shows that we cannot update item in Tuple in Python.
Delete Tuple in Python
Previously we said that tuple items cannot be removed in Python because tuples are immutable. On the contrary, whole tuple can be deleted in Python. To do that we are going to use del keyword as shown below. del keyword is used in Python to delete any data type object.
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") del my_tuple print(my_tuple)
Output:
NameError: name 'my_tuple' is not defined
As output, we get a NameError because after deletion Python will not recognise my_tuple as data type object. So, my_tuple is undefined object now.
Unpacking a Tuple in Python
In Python, tuple unpacking is another way to access items present in the tuple. To unpack a tuple in Python, we must define some variables. The number of variables we defined must be equal to the length of the tuple. For example, to unpack a tuple containing two items, we must define two variables. Each variable will represents one item present in the tuple.
For example,
my_tuple = ("mango", "orange", "banana") a, b, c = my_tuple print(a, b, c)
Output:
mango orange banana
In above Python code, we defined three variables named respectively a, b and c because the tuple object my_tuple contains three items. At the second line , we’re unpacking the tuple named my_tuple by assigning to the variables. First item present in the tuple is assigned to variable a, second item is assigned to variable b, then third item is assigned to variable c. So, variables a, b and c correspond to “mango”, “orange” and “banana” respectively.
Another way of Unpacking Tuple in Python
Apart from the previous way used to unpack tuple in Python, there is another way of unpacking tuple in Python as shown below.
my_tuple = ("mango", "orange", "banana") print(* my_tuple)
Output:
mango orange banana
To unpack tuple in Python, we can also use multiplication operator *. The multiplication operator is placed in front of the tuple object.
Traverse or Iterate Tuple in Python
Now, we will learn how to iterate or traverse tuple in python and display each item present in that tuple through Loop in Python.
-
Traverse Tuple Using for Loop
Python Tuple can be traversed using for loop as shown below –
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") for item in my_tuple : print(item, end=" ")
Output:
mango guava avocado orange pineapple
Through this Python code we want to display each item present in my_tuple by using for Loop.
Inside for loop, item variable stores element present in my_tupple at that position. After element is stored into item, we display it with the print() function.
-
Traverse Tuple Using while Loop
Tuple can be traversed using while loop as shown below –
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") index = 0 length = len(my_tuple) while index < length : print(my_tuple[index], end=" ") index += 1
Output:
mango guava avocado orange pineapple
Here,
– my_tuple is Tuple.
– Variable index stores position in while loop.
– At first iteration, index = 0, length = 5. So, index is less than length. So, code inside while loop is executed. It prints first item in tuple. Then, value of index is increased by 1. So, index = 1.
– At second iteration, index is less than length. So, code inside while loop is executed. it is repeated until index becomes 5. Then, index is not less than length. So, while loop is terminated.
Tuples Operations
In this section, we are going to talk about some operations with tuples in Python. They are –
-
Concatenate or Join Tuples in Python
We can join two or more tuples by using the operator +. For example,
my_fruit = ("mango", "guava") other_fruit = ("avocado", "orange", "pineapple") my_tuple = my_fruit + other_fruit print(my_tuple)
Output:
('mango', 'guava', 'avocado', 'orange', 'pineapple')
At first,
We defined two tuples my_fruit and other_fruit.
Then, we joined these tuples using + operator and assigned it to new tuple – my_tuple.
At last, all elements of joined tuple are printed using print() method. So, output is (‘mango’, ‘guava’, ‘avocado’, ‘orange’, ‘pineapple’) -
Multiply Two Tuples in Python
We can multiply tuples by using the operator of multiplication *. For example,
my_tuple1 = (1, 2, 3, 4, 5) print(my_tuple1 * 2)
Output:
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Here,
my_tuple1 * 2 means my_tuple1 will be repeated twice. -
Check if Element Exists in Tuple or Not
Here, we are going to verify if an item is present in a tuple. We will we use operators in and not in. The result is a boolean which equals to True if condition is verified and False otherwise.
Using in Operator with Tuple
We can use python in operator with Tuple and check if given element exists in tuple or not. It returns True if item is present. Otherwise it returns False. For example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print("apple" in my_tuple)
Output:
False
“apple” is not present in my_tuple. So, output is False.
Let’s take another example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") "guava" in my_tuple
Output:
True
Since “guava” is present in my_tuple. Hence, output is True.
Using not in Operator With Tuple
We can also use not in operator with Tuple to check if item exist in Tuple or not. It returns True if item is not present. Otherwise, it returns False. For example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") "apple" not in my_tuple
Output:
True
“apple” is not present in Tuple my_tuple. Hence, output is True.
Let’s take another example,
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") "guava" not in my_tuple
Output:
False
“guava” is present in my_tuple. Hence, output is False.
Tuple Methods in Python
Some methods or operators used with Tuple in python are as below –
Method | Description |
count() | Returns the number of occurrences of value. In simpler way, it returns number of times the given value appear in a tuple. |
index() | Returns the index of first occurrence of the element in given tuple. Raises ValueError if element is not present in the tuple. |
Built-in functions and Keywords working with tuples.
Functions/Keywords | Description |
len() | Returns the length or the number of elements of the tuple passed as argument. |
tuple() | Creates an empty tuple if no argument is passed. Or, a tuple if a sequence is passed as argument. |
sorted() |
|
max() | Returns the maximum or largest element of the tuple. |
min() | Returns the minimum or smallest element of the tuple. |
sum() | Returns the sum of elements of tuple. |
del | Keyword del is used in Python to delete or remove completely a variable. In our case it is used to remove completely a tuple object. |
Nested Tuples in Python
Till now, we learnt about Tuples in Python. Now, we will talk about Nested Tuple in python. Nested Tuples are Tuples that contain another tuples. Clearly, a Tuple inside another Tuple is called Nested Tuples in Python. For example,
my_tuple = (("mango", "guava", "avocado") , (1, 2, 3, 4, 5))
Here, variable my_tuple is a tuple object because it is created by using parenthesis. So, items are enclosed in parenthesis. Variable my_tuple is also nested tuple because as we said it is a tuple that contains (“mango”, “guava”, “avocado”), (1, 2, 3, 4, 5) which are also tuples.
Now, we are going to discover how nested tuples can be created through the following section.
Create Nested Tuples in Python
As we said above, nested tuples in Python are tuples that contain another tuples. To create nested tuples in Python we will use parenthesis.
my_tuple = (("mango", "guava", "avocado") , "orange", ("pineapple", "apple"))
Converting List to Tuple
List object can be also converted in a tuple. After conversion to Tuple, we cannot modify any items in the new tuple object. To convert list into tuple we are going to use the constructor tuple(). For example,
my_tuple = tuple([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(my_tuple)
Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Here, list object, i.e. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], is converted into tuple object (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) by using the constructor tuple(). Then, it is assigned to my_tuple and printed using print() method.
Let’s take another example,
my_tuple = tuple(["mango", "guava", "avocado", "orange", "pineapple"]) print(my_tuple)
Output:
('mango', 'guava', 'avocado', 'orange', 'pineapple')
Here, list object, i.e. [“mango”, “guava”, “avocado”, “orange”, “pineapple”], is converted into tuple object (‘mango’, ‘guava’, ‘avocado’, ‘orange’, ‘pineapple’) by using the constructor tuple().
Note : Tuple object can be converted to list object by using the constructor list().
Converting Tuple into List
Recently, you have seen that list object can be converted into tuple object by using the constructor tuple(). In the same way, tuple object can be converted into list object by using the constructor list(). For example,
my_tuple = list(("mango", "guava", "avocado", "orange", "pineapple")) print(my_tuple)
Output:
['mango', 'guava', 'avocado', 'orange', 'pineapple']
Here, tuple , i.e. (“mango”, “guava”, “avocado”, “orange”, “pineapple”), is converted to list object
[‘mango’, ‘guava’, ‘avocado’, ‘orange’, ‘pineapple’] using list() constructor.
Difference between Tuple and List in Python
Tuple is an immutable data type. It means that items of a tuple can not be changed after it has been created whereas list items are mutable. Then, elements of list can be modified, changed after list is defined.
In another side, tuple items are enclosed in parenthesis () whereas list items are enclosed in square brackets [ ].
Above all Tuple and List are Built-in data structure and are used to store different data types.
15 Multiple Choice Questions on Tuples and Nested Tuples in Python
1. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") my_tuple.clear() print(my_tuple)
a.) ( )
b.) SyntaxError
c.) Tuple object has no attribute clear
d.) None
2. Which of the following statement are wrong about Tuple in Python ?
a.) Tuple are mutable
b.) We cannot add an item to a tuple
c.) Tuple are immutable
d.) We cannot delete tuple items
3. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") del my_tuple[2] print(my_tuple)
a.) (“mango”, “guava”, “orange”, “pineapple”)
b.) (“mango”, “avocado”, “orange”, “pineapple”)
c.) Tuple object doesn’t support item deletion
d.) None
4. What are the right syntax to create an empty tuple in Python ?
a.) (5, )
b.) { }
c.) [ ]
d.) ( )
e.) tuple()
5. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple[5])
a.) pineapple
b.) orange
c.) IndexError
d.) None
6. What will be the output of the following code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple.index("pineapple"))
a.) 5
b.) 4
c.) ValueError
d.) IndexError
7. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(list(my_tuple))
a.) [“mango”, “guava”, “avocado”, “orange”, “pineapple”]
b.) Error, tuple object cannot be converted into a list object.
c.) TypeError.
d.) None
8. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(my_tuple.index("apple"))
a.) 5
b.) 4
c.) None
d.) ValueError
9. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(sorted(my_tuple))
a.) (“avocado “, “guava”, “mango”, “orange”, “pineapple”)
b.) [‘avocado’, ‘guava’, ‘mango’, ‘orange’, ‘pineapple’]
c.) [‘avocado’, ‘pineapple’, ‘mango’, ‘orange’, ‘guava’]
d.) Error, tuple object cannot be sorted.
10. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(max(my_tuple))
a.) guava
b.) avocado
c.) pineapple
d.) orange
11. Choose the correct output.
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") print(min(my_tuple))
a.) guava
b.) avocado
c.) pineapple
d.) orange
12. Give the output of this Python code.
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") for i in range(0, 5, 2) : print(my_tuple[i], end=" ")
a.) mango guava avocado
b.) mango avocado pineapple
c.) mango orange pineapple
d.) mango pineapple avocado
13. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") del my_tuple print(my_tuple)
a.) (“mango”, “guava”, “avocado”, “orange”, “pineapple”)
b.) None
c.) ()
d.) NameError
14. What will be the output of this Python code ?
my_tuple = ("mango", "guava", "avocado", "orange", "pineapple") my_tuple.pop(2) print(my_tuple)
a.) (“mango”, “avocado”, “orange”, “pineapple”)
b.) (“mango”, “guava”, “orange”, “pineapple”)
c.) AttributeError, tuple object doesn’t have attribute pop.
d.) None
15. Choose the right statements.
a.) Tuple are unordered and List are mutable.
b.) List are immutable and Tuple are ordered.
c.) List are unordered and Tuple are immutable.
d.) List are ordered and Tuple are immutable.
e.) List are mutable and Tuple are ordered.
That’s end of tutorial on Python Tuple and Nested Tuple. Visit official website for more.
You must be logged in to post a comment.