Page 413 - Ai_417_V3.0_C9_Flipbook
P. 413

The insert( ) Function

                 The insert() function is used to add a single value at a specific position in an existing list. The length of the
                 list will increase by one. The syntax of the insert() function is:


                   list.insert(index, value)
                 For example,

                                                 Commands                          Output


                                      L = [10, 20, 30]                   [10, 40, 20, 30]
                                      L.insert(1, 40)
                                      print(L)
                                      L = [10, 20, 30]                   ['abc', 10, 20, 30]
                                      L.insert(0, "abc")
                                      print(L)

                                      L = [10, 20, 30]                   [10, 20, 'xyz', 30]
                                      a = "xyz"
                                      L.insert(2, a)

                                      print(L)
                                      L = [10, 20, 30]                   [10, ['a', 'b'], 20, 30]
                                      L.insert(1, ["a", "b"])
                                      print(L)


                 Modifying Existing Values in a List
                 List is mutable so data can be easily modified by overwriting a new value to an existing value in a given list by
                 using an assignment operator (=). Syntax to modify existing values in a list is:

                   list[index] = newvalue
                 For example,

                                            Commands                             Output


                                   L1=[10,20,40,50]                [10, 20, 40, 100]
                                   L1[3]=100
                                   print(L1)

                                   L1=[10,20,40,50]                [10, 'abc', 'xyz', 100]
                                   L1[1:3]=["abc","xyz"]
                                   print(L1)


                 Removing Elements from a List

                 There are two different functions used to remove elements in an existing list remove() and pop(). Let us learn
                 about these functions in detail.





                                                                                        Introduction to Python  411
   408   409   410   411   412   413   414   415   416   417   418