Page 319 - AI Ver 1.0 Class 9
P. 319

list.remove(<single value>)
            For example,

                                       Commands                                      Output

                     marks = [23, 34, 23, 45, 56, 78, 56]              marks = [34, 23, 45, 56, 78, 56]
                     marks.remove(23)
                     print(marks)
                     marks.remove(56)                                  marks = [34, 23, 45, 78, 56]
                     print(marks)
                     marks.remove(72)                                  ValueError: list.remove(x): x not in list

            The pop( ) Function
            The pop( ) function removes an element from the list based on the index number specified in the function and
            returns the deleted value. In case no index number is given then by default it removes the last element from the
            list. If we try to remove an index number which does not exist then it gives an IndexError. For example,
                                       Commands                                     Output

                     vowels=['a', 'e', 'i', 'o', 'u']                 'i'

                     val=vowels.pop(2)
                     print(val)
                     val=vowels.pop()                                 'u'
                     print(val)
                     val=vowels.pop(6)                                IndexError: pop index out of range
                     print(val)
                     lst=[]                                           IndexError: pop from empty list

                     lst.pop()

            Some other Functions Used with List
            There are some other functions also available to use with the list which are as follows:
               • len(): This function returns the length of a list. For example,

                    marks = [10, 34, 42, 21, 45]

                     print(len(marks))
               Output will be 5
               • clear(): This function removes all the elements of the list in one go. It empties the list but the empty list still
              exists in Python which can be used later to fill the values. For example,

               city=["Delhi", "Mumbai", "Kolkata", "Chennai"]

              city.clear()
              print(city)
               Output will be: [ ]
               • reverse(): This function reverses the content of the list "in place". For example,

               alpha = ['a', 'b', 'c', 'd', 'e']
              alpha.reverse()

                                                                                Introduction to Python  317
   314   315   316   317   318   319   320   321   322   323   324