This note will cover Python Tuples and understand what operations we can perform on the tuples. And after completion of this note, we will be able to use Python Tuples smoothly.
Python Tuples
A tuple is very much similar to a list. However, one of the significant differences between Tuple and List is that List is a mutable data structure. It means we can modify data elements from the List. Whereas tuple is an immutable data structure, we can’t change or alter it once a data element is assigned.
Creating Tuples
We create a tuple using parenthesis () and with or without initialization with the data elements. The creation of tuples are illustrated using the below example code:
In the exatple code, we have created tuples with different data types such as string, integers, and nested tuples that contain multiple data objects.
# Create an empty tuple tup = () # Create tuple with string element tup = ("a","b","c","d","e","f","g") # Output: ('a', 'b', 'c', 'd', 'e', 'f', 'g') # Create tuple with integer element tup = (1,2,3,4,5,6,7) # Output: (1, 2, 3, 4, 5, 6, 7) # Create tuple with mixed data type elements tup = (1,2,3,4,5,6,7) # Output: (1, 2, 3, 4, 5, 6, 7) # Nested tuple as it contains tuple inside tuple as (6,7,8,9) tup = ("a","b","c",[1,2,3,4,5],(6,7,8,9)) # Output: ('a', 'b', 'c', [1, 2, 3, 4, 5], (6, 7, 8, 9))
When there is a single string data element, the Python interpreter considers it a string rather than a tuple. To make it a tuple, we need to keep more than one data element or put a comma (,) that makes it a tuple after the first data element. For example:
tup = ('notepub.io') print(type(tup)) # Output: <class 'str'> tup = ('notepub.io',) print(type(tup)) # Output: <class 'tuple'> tup = ("notepub.io","[email protected]") print(type(tup)) # Output: <class 'tuple'>
And even there is no compulsion to put parenthesis at the start and end while creating a tuple. Instead, we can create it without parenthesis. For example:
tup = "notepub.io", print(type(tup)) # Outupt <class 'tuple'>
Access elements of a Tuple
The elements or items of a tuple can be accessed using indexing. To access from the front, we use index = 0 for the first element, and for the next elements, use index number as an increasing order. Whereas, to access the element in the reverse order, use negative one and so on until starting the element index value.
Access data element from the front
In the below example, we have three data elements in the tuple. Using the index values like 0, 1, and 2, we are accessing the tuple elements.
tup = ("notepub.io","[email protected]","notes.notepub.io") # There are three elements in the tuples, and we will access elements one by one from the front. print(tup[0]) print(tup[1]) print(tup[2]) # Output: notepub.io # Output: [email protected] # Output: notes.notepub.io
Access data element from the back
In the below example, we have three data elements in the tuple as we want to access elements in reverse order. We use a negative sign in front of the index number or value to access the tuple elements from the reverse order.
tup = ("notepub.io","[email protected]","notes.notepub.io") # There are three elements in the tuples, and we will access elements one by one from the back. print(tup[-1]) print(tup[-2]) print(tup[-3]) # Output: notes.notepub.io # Output: [email protected] # Output: notepub.io
Access nested tuple elements
As we know, that tuple can consist of multiple data types, including tuples as well. To access elements from the nested tuple, we do as follows:
tup = ("notepub.io","[email protected]",("notes.notepub.io",)) print(type(tup[0])) print(type(tup[1])) print(type(tup[2])) # Output: <class 'str'> # Output: <class 'str'> # Output: <class 'tuple'>
In the below example code, we can see that there is a list containing two data elements inside the tuple. To access elements from the list, we do as follows:
tup = ("notepub.io","[email protected]",["note.notepub.io","course.notepub.io"]) print(type(tup[2])) print(tup[2]) # Output: <class 'list'> # Output: ['note.notepub.io', 'course.notepub.io'] print(type(tup[2][0])) print(tup[2][0]) # Output: <class 'str'> # Output: note.notepub.io print(type(tup[2][1])) print(tup[2][1]) # Output: <class 'str'> # Output: course.notepub.io
Slicing of Tuple
Slicing is a technique through which we can select a range of data elements from the tuple. Its syntax is [start index number, colon, end index number].
Index value always starts from zero in case of access data elements from the front. However, in the case of backward access, it always starts from -1.
courses = ("Software Engineering","Data Science","Python Programming", "Golang") print(courses) # Output: ('Software Engineering', 'Data Science', 'Python Programming', 'Golang') # To get the elements from index 1 to 3 as a total of three elements. print(courses[1:4]) # Output: ('Data Science', 'Python Programming', 'Golang') # To get the elements from index 2 to 3 as a total of two elements. print(courses[2:4]) # Output: ('Python Programming', 'Golang')
If there is no value before or after the colon, the Python interpreter considers it a default value. The default value for a start is zero, and for an end is the last index value of the tuple.
print(courses[:4]) # Output: ('Software Engineering', 'Data Science', 'Python Programming', 'Golang') # It considers all the data elements from zero index. print(courses[3:]) # Output: ('Golang',) # It considers all the elements from the 3rd index value till the end of the tuple. print(courses[:]) # Output: ('Software Engineering', 'Data Science', 'Python Programming', 'Golang') # It considers all the elements from the tuple. print(courses[:-2] # Output: ('Software Engineering', 'Data Science', 'Python Programming') # It considers all the elements from index 0 to 2nd last.
Change elements in Tuple
As a tuple is a non-mutable data structure, changes are not allowed. It means, once we have created it, we can’t alter it.
courses = ("Engineering","Data Science",["Python Programming", "Golang"]) courses[0] = "Software Development Life Cycle" print(courses[0]) # Output: TypeError: 'tuple' object does not support item assignment courses = ("Engineering","Data Science",["Python Programming", "Golang"]) courses[2][0] = "Python Programming Language" print(courses) # Output: ('Engineering', 'Data Science', ['Python Programming Language', 'Golang']) # As we can see, we can change tuple element when it is list element.
Concatenate Tuples
Tuples can be easily concatenated using the plus (+) operator. In this example, we have two tuples, course1 and course2, and we want to join these two tuples into a single tuple named course. It works as follows:
course1 = ("Software Engineering","Data Science") course2 = ("Python Programming", "Golang") courses = course1 + course2 print(courses) # Output: ('Software Engineering', 'Data Science', 'Python Programming', 'Golang')
Repeat the same elements multiple times within a tuple
The repeat operator is exciting, and it helps create data elements of the same value multiple times. And it works with any data type. In the below examples, we have used almost all the data types and illustrated them as follows.
student_grade = ('A','B',('B',)*4,('A',)*3) print(student_grade) # Output: ('A', 'B', ('B', 'B', 'B', 'B'), ('A', 'A', 'A')) # Note: comma place very important role, just refer second example with comma operator student_grade = ('A','B',('B')*4,('A',)*3) print(student_grade) # Output: ('A', 'B', 'BBBB', ('A', 'A', 'A')) student_grade = (['A',]*4,'B',('B',)*4,('A',)*3) print(student_grade) # Output: (['A', 'A', 'A', 'A'], 'B', ('B', 'B', 'B', 'B'), ('A', 'A', 'A')) student_name = "string "*4 print(student_name) # Output: string string string string student_roll_number = (4,)*4 print(student_roll_number) # Output: (4, 4, 4, 4)
Delete tuple
As we have seen in the earlier section, we can’t change elements of a tuple that also means we can’t delete or remove data elements or items from a tuple. However, it is straightforward to delete the entire tuple by just using the del keyword
courses = ("Engineering","Data Science",["Python Programming", "Golang"]) del courses print(courses) # Output: NameError: name 'courses' is not defined
Built-in Functions used for Tuple
Many built-in functions provide a lot of functionalities to ease operations for tuples.
Count the number of times an element repeated in a Tuple
It counts the number of times an element occurs in a tuple. This operation is useful when we want to count the absolute frequency of each element present in the tuple. For example:
num_tup = (1,2,3,4,5,4,3,23,2,3,4,5,6,7,8,9,0,1,2,3,4,5,56,7,8,8) print(num_tup.count(2)) # Output: 3 char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B','C','D','E','A',) print(char_tup.count('A')) # Output: 6
Find the index number of an element that occurred in a Tuple
It returns the index number of an element that occurs the first time in a tuple.
num_tup = (1,2,3,4,5,4,3,23,2,3,4,5,6,7,8,9,0,1,2,3,4,5,56,7,8,8) print(num_tup.index(2)) # Output: 3
Find an item or element that exists in a tuple or not
It is a useful function when we want to check whether the item is present in the tuple or not. And as an output, it returns True or False.
char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B','C','D','E','A',) print('A' in char_tup) # Output: True
Find the length of the tuple
To find the length of the tuple, we can use the inbuilt function called len. And we will understand it with an example:
char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B','C','D','E','A',) print(len(char_tup)) # Output: 18
Sort items or elements in Tuple
To sort the entire tuple, we can use Python inbuilt function called sorted. However, it has few limitations. It can only sort the tuple whose datatype is symmetric. We can write our custom function for asymmetric data type within a tuple and pass it via key keyword.
char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B','C','D','E','A',) sort_output = sorted(char_tup) print(sort_output) # Output: ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'E', 'E', 'E'] char_tup = ('A','B','C','D',('E','A','A','B','C'),'D','E',('A','A','B','C'),'D','E','A') sort_output = sorted(char_tup) print(sort_output) # Output: TypeError: '<' not supported between instances of 'tuple' and 'str' char_tup = ('A','B','C','D',['E','A','A','B','C'],'D','E',('A','A','B','C'),'D','E','A',) sort_output = sorted(char_tup) print(sort_output) # Output: TypeError: '<' not supported between instances of 'list' and 'str'
Find the largest or max item or element from the Tuple
To find the maximum or largest element from the tuple, we can use Python built-in max function. This function works well when the data type is symmetric. It means all the elements in the tuple must be the same data type. It is illustrated with the help of the below examples:
char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B') max_element = max(char_tup) print(max_element) # Output: E num_tup = (1,2,3,4,5,4,3,23,2,3,4,5,6,7,8,9,0,1,2,3,4,5,56,7,8,8) max_element = max(num_tup) print(max_element) # Output 56 mix_tup = ('A','B','a','D','E','A','Z','B',1,2,4,5,3,6,"notepub.io") max_element = max(mix_tup) print(max_element) # Output: TypeError: '>' not supported between instances of 'int' and 'str' nested_char_tup = ('A','B','C','D',['E','A','A','B','C'],'D','E',('A','A','B','C')) max_element = max(nested_char_tup) print(max_element) # Output: TypeError: '>' not supported between instances of 'list' and 'str'
Find the smallest or min item or element from the Tuple
To find the minimum or smallest element from the tuple, we can use the Python inbuild min function. This function works well when the data type is symmetric. It means all the elements of the tuple must be the same data type. It is illustrated with the help of the below examples:
char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B') min_element = min(char_tup) print(min_element) # Output: A num_tup = (1,2,3,4,5,4,3,23,2,3,4,5,6,7,8,9,0,1,2,3,4,5,56,7,8,8) min_element = min(num_tup) print(min_element) # Output: 0 mix_tup = ('A','B','a','D','E','A','Z','B',1,2,4,5,3,6,"notepub.io") min_element = min(mix_tup) print(min_element) # Output: TypeError: '>' not supported between instances of 'int' and 'str' nested_char_tup = ('A','B','C','D',['E','A','A','B','C'],'D','E',('A','A','B','C')) min_element = min(nested_char_tup) print(min_element) # Output: TypeError: '>' not supported between instances of 'list' and 'str'
Find the sum of the elements of the tuple
To find the sum of the tuple elements, we can use the Python inbuilt sum function. This function works only when the data type is symmetric and real numbers. It is illustrated with the help of the below examples:
num_tup = (1,2,3,4,5,4,3,23,2,3,4,5,6,7,8,9,0,1,2,3,4,5,56,7,8,8) sum_of_elements = sum(num_tup) print(sum_of_elements) # Output: 183 char_tup = ('A','B','C','D','E','A','A','B','C','D','E','A','A','B') sum_of_elements = sum(char_tup) print(sum_of_elements) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
When to use Tuple vs List
One of the significant differences between tuple and list is that tuples are immutable and lists are mutable. When there is a requirement of keeping the records as read-only, then the tuples are the best data structure as it provides immutability. Python interpreters can easily detect if some piece of code tries to modify a tuple.
110 total views, 1 views today