Page 257 - Ai_V1.0_Class9
P. 257

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.


                 The remove( ) Function
                 The remove() function removes the first occurrence of the element with the specified value. It means only one
                 value can be removed at a time even if there are duplicate values in the list. If you wish to remove multiple values
                 then this function can be used within a loop where it repeats itself a specific number of times. The syntax of the
                 remove() function is:
                    list.remove(<single value>)

                 For example,

                                            Commands                                      Output
                          marks = [23, 34, 23, 45, 56, 78, 56]              [34, 23, 45, 56, 78, 56]
                          marks.remove(23)
                          print(marks)
                          marks = [23, 34, 23, 45, 56, 78, 56]              [23, 34, 23, 45, 78, 56]
                          marks.remove(56)

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


                 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.



                                                                                        Introduction to Python  255
   252   253   254   255   256   257   258   259   260   261   262