Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 157 - CodePilot V5.0 C8
P. 157

    The output of the preceding code would be as follows:

                         Output
                      List of Exam Subjects: ['Math', 'Science', 'English', 'History', 'Computer']
                      Using Positive Indexing:
                      The first exam subject is: Math
                      The third exam subject is: English
                      Using Negative Indexing:
                      The last exam subject is: Computer
                      The second last exam subject is: History

                     MODIFYING THE LIST ELEMENT
                     Lists are mutable, which means you can change the elements after the list is created without
                     creating a new space for storage of the changed list. You can do this by using an assignment
                     operator (=).

                      Program 17 A program to change the elements of a list.

                         Program17.py
                      File  Edit  Format   Run    Options   Window    Help

                      exam_subjects = ["Math", "Science", "English", "History", "Computer"]
                      print("List of Exam Subjects:", exam_subjects)
                      exam_subjects[1]="French"
                      exam_subjects[3]="Social Studies"
                      print("List of Modified Exam Subjects:",exam_subjects[:])

                     The output of the preceding code would be as follows:

                         Output
                      List of Exam Subjects: ['Math', 'Science', 'English', 'History', 'Computer']
                      List of Modified  Exam Subjects:  ['Math', 'French',  'English',  'Social
                      Studies', 'Computer']

                     SLICING THE LIST
                     List slicing refers to a part of a list. In Python, list slicing is done by using the Slicing operator(:). The
                     syntax of slicing the list is as follows:

                     name of the list[ start : stop : step ]
                     start is the start position of the list.
                     stop is the end position of the list.
                     step is the increment of the list (the step parameter is optional and by default is 1).

                                                                                                                      155
                                                                                                Step Ahead with Python

| 152 153 154 155 156 157 158 159 160 161 162 |