Python Programming – Python Tuples
In the Python programming language, a tuple is another important data structure. A tuple is similar to a Python list as studied in the previous section. The difference between tuple and list is that the elements in a list can be altered, whereas tuples are immutable, i.e., the elements of a tuple can not be changed.
Creating a Tuple
Alike a list, it is very simple to create a tuple in Python. As we see earlier that the elements of a list are enclosed in square brackets [ ], whereas the elements of a tuple are enclosed in parenthesis ( ) separated with commas. Moreover, a tuple can have any number of elements of heterogeneous type (integer, float, string_list, etc). The programming illustration to create different kinds of tuples is given in Code 5.19. In this program, we create three tuples.
The first tuple new tuple is of homogeneous data elements. The second tuple new_tuplel contains heterogeneous type data and the third tuple new_tuple2 represents the nested tuple, which also contains a list as its data element. The output for the same is given as well.
- Python Programming – Tuple
- Python Programming – Tuple Functions
- Python Programming – Common Tuple operations
Code: 5,19. Illustration of creating a tuple.
|#Illustration of creating a tuple
new_tuple=(l, 2, 3, 4) # Homogeneous data elements
new_tuplel=(l, “John”, 55.5) # Heterogeneous data elements
new_tuple2=[ 111, [1, “Clara”, 75.5], (2, “Simon”, 80.5)]# Nested tuple
The unpacking refers to separating members or elements of a tuple. Unpacking may be helpful for further processing tuple elements individually. The unpacking can be performed very easily as shown in Code 5.20. It is apparent from the output that the tuple elements can be separated for further use. In this program, the first element of the tuple is assigned to x, the second element is assigned to y, and the third element is assigned to z. The programmer must take care while unpacking of tuple as the number of variables must match the number of elements of the tuple otherwise ValueError occurs.
Code:, 5.20. Illustration of unpacking elements of a tuple.
|#Illustration of unpacking a tuple
new_tuple2=(l 11, [1, “Clara”, 75.5], (2, “Simon”, 80.5))# Nested tuple
print(new_tuple2)x, y, z=new_tuple2
Traversing Elements in a Tuple
As we have performed traversing of a list in the previous section, a similar concept is applicable over the tuple also. In the following sub-sections, we discuss the tuple traversing methods.
Alike list the index of a tuple also starts from 0 and the index or subscript operator  is used to access the elements of a tuple. If a tuple contains 10 elements then the index value of the tuple varies from 0 to 9. Moreover, the index value must be an integer otherwise it will result in TypeError. The programming example to access elements of a tuple is presented in Code 5.21. In this program, a nested tuple is created with the name data tuple, which contains 3 elements. We access 3 elements individually with indexes 0, 1, and 2. Then nested elements “Clara” and “Simon” are accessed by datatuple[ 1 ] [ 1 ] and datatuple[l].
Code: 5.21. Illustration of traversing a tuple.
|#IllUstration of traversing a tuple
datatuple=(l 11, [1, “Clara”, 75.5], (2, “Simon”, 80.5)) # Nested
As in the Python list, negative indexing is also possible in the tuple. The index -1 refers to the last element, -2 indexes the second last element, and so on. The programming illustration for the same is given in code 5.22. We can see from the program that the process of negative indexing is useful for traversing the tuple in reverse order.
Code: 5.22, Illustration of traversing a tuple by negative indexing.
|#Illustration of traversing a tuple through negative indexing
datatuple=(111, [1, “Clara”, 75.5], (2, “Simon”, 80.5)) # Nested
(2, ‘Simon’, 80.5)
[1, ‘Clara’, 75.5]
In order to access tuple elements for a certain range, the slicing operator [:] is used. The programming example for using the slicing operator is given in Code 5.23. The slicing operator for tuple works the similar way as for list.
Code: 5.23, Illustration of slicing operator.
|#Illustration of traversing a tuple by slicing operator
datatuple=(‘P’, ‘Y’, T, TT, ’O’, ’N’)
Changing/Updating a Tuple
As we know that tuples are immutable that means the elements of a tuple cannot be changed. However, if a tuple contains a list as its member then that member can be altered by using the index value of the list element. The programming example is given in Code 5.24. In this program, we see that only the list element at index value 1 can be altered. We change the value of “Clara” to “Sharon”.
Code:5.24. Illustration of altering a tuple.
|#Illustration of altering a tuple
new_tuple=(111, [1, “Clara”, 75.5], (2, “Simon”, 80.5))
(111, [1, ‘Sharon’, 75.51, (2, ‘Simon’, 80.5))
Deleting a Tuple
As mentioned in the previous section that the elements of a tuple cannot be altered. It implies that the elements of a tuple cannot be deleted or removed. However, we can delete the entire tuple by using the del keyword. This concept is illustrated in Code 5.25. If a user tries to print the deleted tuple then it will result in an error as shown in the output section.
Code 5.25. Illustration of deleting a tuple.
|#Illustration of deleting a tuple
datatuple=(’P’, V, T, ‘H’, ’O’, TST’)
Python Tuple Methods
Since tuples are immutable, add and remove methods are not provided with tuples. The Python language contains only two methods for tuples, which are given in Table 5.6.
|count(p)||It returns the number of times p occurs in the tuple|
|index(p)||It returns are an index of the first element in tuple, which is equal to p|
The programming illustration of the above methods is almost similar to that of the list. Therefore, it is left as an exercise for the reader. Apart from that, the membership of an element of a tuple can be performed in the same way as that for the list. The ‘in’ operator is used to determine the presence of an element in the tuple. If the element is present it returns true otherwise false. The ‘in’ operator can also be used for iterating through a tuple using for loop. The programming illustration is given in Code 5.26. In this code, it is apparent that all the elements of a tuple can be accessed efficiently using the in operator and for a loop.
Code: 5.26. Illustration of accessing a tuple using for loop.
|#Illustration of ‘in’ operator with tuple
for str in (‘Bread’, ‘Butter’, ‘Jam’):
I love Bread
Python Tuple Functions
Apart from the tuple methods, the Python language also provides various tuple functions which are given in Table 5.7. with the description of each.
|Len( )||Returns the total number of elements in the tuple|
|max()||Returns the largest element in the tuple|
|min()||Returns the smallest element in the tuple|
|sum()||Returns the sum of all the elements of the tuple|
|sort()||Returns the sorted list of elements of the tuple|
|enumerate()||Returns the enumerated object of the tuple|
|all()||Returns true if all the elements of the tuple are true|
|any()||Returns true if any element of the tuple is true|
Advantages of Tuple
Tuples are assumed to be similar to the lists with the major difference that tuples’ are immutable. Due to this feature, the tuple possesses certain advantages over the Python list as given below:
- The iteration over tuple is faster than the list due to the immutability of tuples.
- In order to provide write protection to the data, tuples can be used.
- Tuples containing immutable elements can be used as a key for a dictionary, which is not feasible with the list.
- Although list and tuple both can contain heterogeneous data elements. However, usually, tuples are used to contain heterogeneous data elements, and lists are used to contain homogeneous data.