Page 194 - Information_Practice_Fliipbook_Class11
P. 194

●  lst.reverse(): The method reverse() reverses the order of the elements in the list. For example,

         >>> names = ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
         >>> names.reverse()
         >>> names
              ['Venkatesh', 'Sunpreet', 'Samantha', 'Anthony', 'Aryan']
        ●  lst.sort(): The method arranges the elements of the list in ascending order.

        Example:
         >>> names.sort()
         >>> names
              ['Anthony', 'Aryan', 'Samantha', 'Sunpreet', 'Venkatesh']
        To sort the elements in a list in descending order, we set the argument reverse = True, as shown below:

         >>> names = ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
         >>> names.sort(reverse = True)
         >>> names
              ['Venkatesh', 'Sunpreet', 'Samantha', 'Aryan', 'Anthony']


               When the argument key=function is specified, the function is applied to each element of the list, and the
               values in the list are arranged according to the ascending order of the function values. For example, we define a
               function f(x) which returns 1/x.
               >>> def f(x):
               ...     return 1/x
               ...
               >>> lst = [4, 16, 10, 2]
               >>> lst.sort(key=f)
               >>> lst
                   [16, 10, 4, 2]
               Applying the function f to the elements 4, 16, 10, 2 of lst yields the numbers 1/4, 1/16, 1/10, 1/2. An ascending
               order listing of these numbers would be 1/16, 1/10, 1/4, 1/2. As this listing of numbers corresponds to the numbers
               16, 10, 4, and 2, respectively, on sorting the list (lst) according to the function values of its elements, we get the list
               [16, 10, 4, 2].


        ●  lst.remove(element): The method remove(element) searches for the first instance of the element in

           the list lst and removes it. If an element is not found in lst, the method remove throws ValueError.
         >>> lst = [10, 20, 30, 10, 50, 20, 60, 20, 30, 55]
         >>> lst.remove(20)
         >>> lst
              [10, 30, 10, 50, 20, 60, 20, 30, 55]
         >>> lst.remove(66)
              Traceback (most recent call last):
                File "<pyshell#7>", line 1, in <module>
                  lst.remove(66)
              ValueError: list.remove(x): x not in list
        ●  The del statement can also be used to remove an element from the list by specifying its index.
         >>> del lst[3]
         >>> lst.pop()
              55
         >>> lst
              [10, 20, 30, 50, 20, 60, 20, 30]









          180  Touchpad Informatics Practices-XI
   189   190   191   192   193   194   195   196   197   198   199