Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 140 - 2609_Logicode
P. 140

    Program 14: To add an element to a list using append() function

                          Program14.py
                       File  Edit  Format    Run   Options   Window    Help

                       a=[1,2,3,4,5]
                       a.append(6)
                       print (a)

                      You will get the following output:

                          Output

                       [1, 2, 3, 4, 5, 6]

                      The extend( ) Function

                      Using the append( ) function, we can only add one element at a time. For adding more than one
                      element, we use the extend( ) function. Syntax of using extend() function is:
                          list_name.extend(iterable value)
                      Program 15: To add elements to an existing list using extend() function

                          Program15.py

                       File  Edit  Format    Run   Options   Window    Help
                       a=[1,2,3,4,5]
                       a.extend([6,7,8,9])
                       print (a)

                          Output
                       [1, 2, 3, 4, 5, 6, 7, 8, 9]

                      THE del STATEMENT
                      We use the del statement to remove an element or a slice of element from a list.
                      Syntax for using del statement is:

                          del list_name[start : stop : step]
                      Program 16: To delete elements from the list

                          Program16.py
                       File  Edit  Format    Run   Options   Window    Help

                       a=[1,2,3,4,5,6,7]
                       del a[1:3:2]
                       print (a)

                      138   Premium Edition-VIII

| 135 136 137 138 139 140 141 142 143 144 145 |