Page 306 - Computer Science Class 11 Without Functions
P. 306

14 wordLenPairs = list()
          15 for word in lst:
          16     wordLenPairs.append((word, len(word)))
          17
          18 print('List of tuples:: ', wordLenPairs)

        Sample Output:
         >>> Enter the list: ['Adorable','Beautiful','Cute','Charming','Attractive']
              List of tuples:: [('Adorable', 8), ('Beautiful', 9), ('Cute', 4), ('Charming', 8),
              ('Attractive', 10)]

        12.12 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. 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)

         304   Touchpad Computer Science-XI
   301   302   303   304   305   306   307   308   309   310   311