Question:
Perform the following operations on the below tuple (‘abc’, ‘def’, ‘ghi’, ‘jklm’, ‘nopqr’, ‘st’, ‘uv’, ‘wxyz’, ’23’, ‘s98’, ‘123’, ’87’)
prints the length of the tuple
Slicing
Reverse all items in the tuple
Removing whole tuple
Concatenate two tuples
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
tup = ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') # prints the length of the tuple print('\ntuple: ', tup) print('Length of the tuple is : ', len(tup)) # Slicing # shows only items starting from 0 upto 3 print('\ntuple: ', tup) print('tuple showing only items starting from 0 upto 3\n', tup[:3]) # shows only items starting from 4 to the end print('\ntuple: ', tup) print('tuple showing only items starting from 4 to the end\n', tup[4:]) # shows only items starting from 2 upto 6 print('\ntuple: ', tup) print('tuple showing only items starting from 2 upto 6\n', tup[2:6]) # reverse all items in the tuple print('\ntuple: ', tup) print('tuple items reversed \n', tup[::-1]) # removing whole tuple del tup tup_0 = ("ere", "sad") tup_1 = ("sd", "ds") print('\nfirst tuple: ', tup_0) print('second tuple: ', tup_1) tup = tup_0 + tup_1 print('Concatenation of 2 tuples \n', tup) |
Explanation:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') Length of the tuple is : 12 tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple showing only items starting from 0 upto 3 ('abc', 'def', 'ghi') tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple showing only items starting from 4 to the end ('nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple showing only items starting from 2 upto 6 ('ghi', 'jklm', 'nopqr', 'st') tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple items reversed ('87', '123', 's98', '23', 'wxyz', 'uv', 'st', 'nopqr', 'jklm', 'ghi', 'def', 'abc') first tuple: ('ere', 'sad') second tuple: ('sd', 'ds') Concatenation of 2 tuples ('ere', 'sad', 'sd', 'ds') |
Leave a Reply