Page 331 - Artificial Intellegence_v2.0_Class_9
P. 331

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()
              print(alpha)
               Output will be: ['e', 'd', 'c', 'b', 'a']
               • sort(): This function sorts the list in ascending or descending order. This is done "in the list itself" and works for
              the list with values of the same data types. For example,

                    city=["Delhi", "Mumbai", "Kolkata", "Chennai"]
                     city.sort() #sorts the list by default in ascending order
                     print(city)




                                                                                   Introduction to Python  329
   326   327   328   329   330   331   332   333   334   335   336