Page 343 - Computer Science Class 11 With Functions
P. 343

4       from statistics  It returns the mean of  the  >>> lst = [1, 2, 3, 4, 5]
                     import mean           elements of a list.             >>> from statistics import mean
                     mean(lst)                                             >>> mean(1st)

                                                                               3

            13.6 List Methods

            Python provides several methods to manipulate  lists. Below, we will discuss some of these methods with an example
            list: lst. These methods do not create a new list; they modify the original list: lst. Such an operation that takes place
            on an existing object is said to be in place.

            ●  lst.append(elem): The method append() inserts the object elem, passed as an argument, at the end of
              the list lst.

             Example:
             >>> lst1 = [10, 20, 30, 40]
             >>> lst1.append(35)
             >>> lst1
                 [10, 20, 30, 40, 35]
            ●  lst.insert(index, elem): The method insert() inserts the object elem, passed as an argument,  at
              the  specified index.
             Example:
             >>> names = ['Aryan', 'Anthony', 'Sunpreet', 'Venkatesh']
             >>> names.insert(2, 'Samantha')
             >>> names
                 ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
            ●  lst.extend(obj): The method extend() inserts the elements in obj, passed as an argument, at the end
              of the elements of the list lst. Note that obj may not necessarily be a list and could as well be a tuple, set, or
              a dictionary
             Example:

             >>> intList = [10, 20, 30]
             >>> intList.extend([40,50])
             >>> intList
                 [10, 20, 30, 40, 50]


                     Assuming that lst is a list, what is the difference between the operations:
                      lst.extend([40,50]) and lst + [40, 50]


            ●  lst.index(elem): The method index() returns the index of the first occurrence of the  element elem in
              the list. If elem does not appear in the list lst, it throws a ValueError, for example,
             >>> names = ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
             >>> names.index('Samantha')
                 2
             >>> name = 'Arjun'
             >>> names.index(name)
                 Traceback (most recent call last):
                   File '<pyshell#3>', line 1, in <module>
                     names.index(name)
                 ValueError: 'Arjun' is not in list






                                                                                                Lists and Tuples  341
   338   339   340   341   342   343   344   345   346   347   348