Nested Tuples in Python
Tuples are similar to the list. A tuple contains number of items separated by commas. The only difference between a list and a tuple is that a list is enclosed with [ ] and the items in it can be changed whereas a tuple is enclosed with ( ) and the items in it cannot be changed. The below is an example that describes the tuple creation.
>>> tuple=( )
>>> tuple ( ) >>> tuple=(“VMS”,16,56,1.5) >>> tuple (‘VMS’, 16, 56, 1.5) |
You can refer basic concept of tuples from the following link:
In Python there is also a concept called as nested tuples. Nested tuples are the tuples which comprises of group of tuples.
Creating a nested tuple:
Creating a nested tuple is almost similar as creating a tuple. Here, a tuple is considered as one of the elements in a nested tuple.
>>> T=(“aeiou”,1,(“vowels”,5,2.98),’xyz’)
>>> T (‘aeiou’, 1, (‘vowels’, 5, 2.98), ‘xyz’) |
Accessing elements from Nested tuple
We can access the elements from a nested tuple by using indexing ‘[ ]’. It is illustrated for the same above example.
>>> T=(“aeiou”,1,(“vowels”,5,2.98),’xyz’)
>>> T[2][0] ‘vowels’ >>> T[1] 1 >>> T[3] ‘xyz’ >>> T[-2][1] 5 |
Updating a Nested tuple
We cannot update or change the elements once after they created. It is only possible on nested elements which are it-self immutable like lists. It is shown in below example.
>>> a=(1,2,[3,4,5])
>>> a (1, 2, [3, 4, 5]) >>> a[2][0]=9 >>> a (1, 2, [9, 4, 5]) >>> a[2][2]=12 >>> a (1, 2, [9, 4, 12]) |
In the above example [3,4,5] is declared as list and is considered as one of the elements in a tuple. Since the lists are mutable so that the elements are updated in such case. Otherwise we cannot update.
Deleting elements in a Nested tuple
We can’t delete an element in a tuple but we can delete an entire tuple using ‘del’ keyword.
>>> del(T) |
Basic operations on nested tuples:
The following are some of the basic operations on tuples.
>>> a=(“Sudhakar”,16,52,(“VMS”),(1,3,5,7),5.26)
>>> a (‘Sudhakar’, 16, 52, ‘VMS’, (1, 3, 5, 7), 5.26) >>> ‘sudhakar’ in a False >>> ‘vms’ in a False >>> ‘VMS’ in a True >>> 16 not in a False >>> >>> (1,2,3,”Python”)+(“xy”,5,2) #Concatenation (1, 2, 3, ‘Python’, ‘xy’, 5, 2) >>> >>> “Sudha”*3 #Repetition ‘SudhaSudhaSudha’ |
Iteration with elements in nested tuple
We can iterate through every element in a nested tuple by using for loops. The below example describes the iteration of an element in tuple.
Output
Cricket
Tennis Hockey Football Badminton |
We can also iterate by passing strings as a parameters. It is shown in below example.
Example program
1.A python program to find the maximum value of elements in a nested tuple.
Output
62 |