Page 353 - Computer Science Class 11 With Functions
P. 353
13.9 Tuple Methods
Python provides several methods for manipulating the tuples. Like a string, a tuple is also an immutable object, All
the methods that operate on a tuple leave the original tuple unchanged. To invoke a method associated with a tuple
object, the tuple object is followed by a dot, followed by the method's name, followed by a pair of parentheses that
enclose the arguments (if any) required for invoking the method. Next, we describe the functionality of some methods
for the tuple objects on a tuple object, say, tpl.
1. tpl.count(value): The method returns the number of occurrences of the given value in a tuple.
Examples:
>>> (0, 1, 2, 3, 2, 3, 1, 3, 2).count(2)
3
>>> age = (20, 18, 17, 19, 18, 18)
>>> age.count(18)
2
>>> age.count(15)
0
2. tpl.index(element): The method returns the index of the first occurrence of an element in a tuple. If the
element being searched does not appear in the tuple, the method yields an error.
Example:
>>> (0, 1, 2, 3, 2, 3, 1, 3, 2).index(3)
3
>>> (0, 1, 2, 3, 4).index(6)
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
(0, 1, 2, 3, 4).index(6)
ValueError: tuple.index(x): x not in tuple
3. sorted(tpl): The method sorts the tuple elements in ascending order by default. However, one can
use the reverse parameter and sets its value to True.
Example:
>>> myTuple = (5, 2, 24, 3, 1, 6, 7)
>>> sorted(myTuple)
[1, 2, 3, 5, 6, 7, 24]
>>> myTuple
(5, 2, 24, 3, 1, 6, 7)
As expected, being immutable, the tuple myTuple remains unaffected, when the method sorted is applied to it.
Indeed, the method sorted()returns a list by default. However, if the result of sorting is desired as a tuple, we may
apply the function tuple() to the list returned by the method sorted(). For example,
>>> tuple(sorted(myTuple))
(1, 2, 3, 5, 6, 7, 24)
>>> tuple(sorted(myTuple, reverse=True))
(24, 7, 6, 5, 3, 2, 1)
Solved Programming Questions
1. Write a function to remove the duplicate elements from a list. You are not allowed to create a new list within the
function. Make use of it to write a program that accepts as input a list from a user and display the list without
duplicates.
01 def removeDuplicates(lst):
02 '''
Lists and Tuples 351

