Tuples
A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas. Like list and string, elements of a tuple can be accessed using index values, starting from 0. Let us take few examples of tuple #tuple1 is the tuple of integers >>> tuple1 = (1,2,3,4,5) >>> tuple1 (1, 2, 3, 4, 5 )
#tuple2 is the tuple of strings
>>> tuple2 = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") >>> tuple2 ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
#tuple3 is the tuple of mixed data types >>> tuple3 = ('Economics', 87, 'Accountancy', 89.6)
>>> tuple3 ('Economics', 87, 'Accountancy', 89.6)
#tuple4 is the tuple with list as an element
>>> tuple4 = (10, 20, 30, [40, 50])
>>> tuple4 (10, 20, 30, [40, 50])
#tuple5 is the tuple with tuple as an element
>>> tuple5 = (1, 2, 3, 4, 5, (10,20)) >>> tuple5 (1, 2, 3, 4, 5, (10, 20))
If there is only a single element in a tuple then the element should be followed by a comma. If we assign the value without comma it is treated as integer. It should be noted that a sequence without parenthesis is treated as tuple by default.
#incorrect way of assigning single element to
#tuple
#tuple5 is assigned a single element
>>> tuple5 = (20)
>>> tuple5 20
>>>type(tuple5) #tuple5 is not of type tuple
#it is treated as integer #Correct Way of assigning single element to #tuple
#tuple5 is assigned a single element
>>> tuple5 = (20,) #element followed by comma
>>> tuple5 (20,)
>>>type(tuple5) #tuple5 is of type tuple
#a sequence without parentheses is treated as
#tuple by default
>>> seq = 1,2,3 #comma separated elements
>>> type(seq) #treated as tuple
>>> print(seq) #seq is a tuple (1, 2, 3)
Accessing Elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing. Let us take few examples to illustrate this.
>>> tuple1 = (2, 4, 6, 8, 10, 12) #initializes a tuple tuple1 #returns the first element of tuple1
>>> tuple1[0]
2 #returns fourth element of tuple1
>>> tuple1[3]
8
#returns error as index is out of range
>>> tuple1[15] IndexError: tuple index out of range #an expression resulting in an integer index >>> tuple1[1+4] 12 #returns first element from right
>>> tuple1[-1] 12
Tuple is Immutable
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it has been created. An attempt to do this would lead to an error as illustrated in the example given below:
>>> tuple1 = (1, 2, 3, 4, 5)
>>> tuple1[4] = 10 TypeError: 'tuple' object does not support item assignment However, an element of a tuple may be of mutable type, e.g., a list. #4th element of the tuple2 is a list
>>> tuple2 = (1, 2, 3, [8, 9]) #modify the list element of the tuple tuple2
>>> tuple2[3][1] = 10 #modification is reflected in tuple2
>>> tuple2 (1, 2, 3, [8, 10])
Tuple Operations
A number of operations like concatenation, repetition, membership and slicing can be performed on tuples. Let us learn these tuple operations one by one.
Concatenation Python allows us to join tuples using concatenation operator depicted by symbol +. We can also create a new tuple which contains the result of this concatenation operation. Let us take few examples to illustrate this. >>> tuple1 = (1, 3, 5, 7, 9) >>> tuple2 = (2, 4, 6, 8, 10) >>> tuple1 + tuple2 #concatenates two tuples (1, 3, 5, 7, 9, 2, 4, 6, 8, 10) >>> tuple3 = ('Red', 'Green', 'Blue') >>> tuple4 = ('Cyan', 'Magenta', 'Yellow' , 'Black') #tuple5 stores elements of tuple3 and tuple4 >>> tuple5 = tuple3 + tuple4 >>> tuple5 ('Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black') Concatenation operator can also be used for extending an existing tuple. When we extend a tuple using concatenation a new tuple is created. >>> tuple6 = (1, 2, 3, 4, 5) #single element is appended to tuple6 >>> tuple6 = tuple6 + (6,) >>> tuple6 (1, 2, 3, 4, 5, 6) #more than one elements are appended >>> tuple6 = tuple6 + (7, 8, 9) >>> tuple6 (1, 2, 3, 4, 5, 6, 7, 8, 9) 15.2.2 Repetition Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple. We can repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the second operand to be an integer only. >>> tuple1 = ('Hello', 'World') >>> tuple1 * 3 ('Hello', 'World', 'Hello', 'World', 'Hello', 'World') #tuple with single element >>> tuple2 = ("Hello",) >>> tuple2 * 4 ('Hello', 'Hello', 'Hello', 'Hello') 15.2.3 Membership The in operator checks if the element is present in the tuple and returns True, else it returns False. >>> tuple1 = ('Red', 'Green', 'Blue') >>> 'Green' in tuple1 True The not in operator returns True if the element is not present in the tuple, else it returns False. >>> tuple1 = ('Red', 'Green', 'Blue' )
>>> 'Green' not in tuple1 False 15.2.4 Slicing Like string and list, slicing can be applied to tuples also. Let us take few examples to illustrate this. #tuple1 is a tuple >>> tuple1 = (10, 20, 30, 40, 50, 60, 70, 80) #elements from index 2 to index 6 >>> tuple1[2:7] (30, 40, 50, 60, 70) #all elements of tuple are printed >>> tuple1[0:len(tuple1)] (10, 20, 30, 40, 50, 60, 70, 80) #slice starts from zero index >>> tuple1[:5] (10, 20, 30, 40, 50) #slice is till end of the tuple >>> tuple1[2:] (30, 40, 50, 60, 70, 80) #step size 2 >>> tuple1[0:len(tuple1):2] (10, 30, 50, 70) #negative indexing >>> tuple1[-6:-4] (30, 40) #tuple is traversed in reverse order >>> tuple1[::-1] (80, 70, 60, 50, 40, 30, 20, 10
Tuple Assignment
Nested Tuples
A tuple inside another tuple is called a nested tuple. In a nested tuple, each tuple is considered as an element. Loop control structures can be used to access the elements in a nested tuple. Let us take few examples of nested tuple.
>>> tuple1 = (1,2,3, (4,5))
>>> tuple1 (1, 2, 3, (4, 5))
>>> tuple2 = ((1,2), (3,4), (5,6))
>>> tuple2 ((1, 2), (3, 4), (5, 6))
Here, (4,5) is a nested tuple as it an element of another tuple tuple1. Similarly, (1, 2), (3, 4) and (5, 6) are nested tuples as these tuples are elements of another tuple tuple2. Nested tuple can be used to represent a specific data record. For example, records of many students consisting RollNo, Name and Marks can be stored in a nested tuple. Let us do an activity to demonstrate the use of nested tuples to store records of students and print them.
Assignment of tuple is a useful feature in Python. It allows a tuple of variables on the left side of the assignment operator to be assigned respective values from a tuple on the right side. The number of variables on the left should be same as the number of elements in the tuple. Let us take an example to illustrate this. #The first element 10 is assigned to num1 and #the second element 20 is assigned to num2.
>>> (num1,num2) = (10,20)
>>> print(num1) 10
>>> print(num2) 20
>>> record = ("Pooja",40,"CS")
>>> (name, rollNo, subject) = record
>>> name 'Pooja'
>>> rollNo 40
>>> subject 'CS'
>>> (a, b, c, d) = (5,6,8) ValueError: not enough values to unpack (expected 4, got 3) If there is an expression on the right side then first that expression is evaluated and finally the result is assigned to the tuple. Let us take an example to illustrate this. #15 is assigned to num3 and #25 is assigned to num4
>>> (num3, num4) = (10+5,20+5)
>>> print(num3) 15
>>> print(num4)
25