Page 403 - Computer Science V2.0 Class 11
P. 403
>>> 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)
The built-in functions for tuple manipulations are summarized in the following table:
Table 13.4: Built-in functions and methods for Tuple
Method Description Example
tpl.count(value) Returns the number of occurrences >>>tuple_t1=('Touchpad',
of the given value in a tuple. 'Computer',
'Science','Computer')
>>>tuple_t1.count('Computer')
2
tpl.index(element) Returns the index of the first >>>tuple_t1=('Touchpad',
occurrence of an element in a tuple. 'Computer',
'Science','Computer')
>>>tuple_t1.index('Computer')
1
sorted(tpl) Sorts the tuple elements in ascending >>>tuple_t1=('Touchpad',
order by default. 'Computer',
'Science','Computer')
>>>sorted(tuple_t1)
('Touchpad', 'Computer',
'Science', 'Computer')
Lists and Tuples 389

