Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 118 - 2615_KEC
P. 118

    Nested List
                      A list can contain other lists as elements, which is known as a nested list.

                      Program 13: To create a nested list
                          Program13.py

                       File  Edit  Format   Run    Options   Window    Help
                                                                                    Output
                       a=['Lakshaya', 'Sameer', 10, 20, [1,2,3],7]
                                                                                  ['Lakshaya', 'Sameer', 10, 20,
                       print (a)
                                                                                  [1, 2, 3], 7]

                      ACCESSING A LIST
                      We use an index number to access the list items just like strings. Use the index operator [ ] to
                      access the elements of a list.

                      Program 14: To access the different elements of a list
                          Program14.py

                       File  Edit  Format    Run   Options   Window    Help

                       List1=[1,2,3,11,12,13,'Computer',40, 'Science']
                       print (List1[2])
                       print (List1[6])
                       print (List1[-2])

                          Output
                       3
                       Computer
                       40

                      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 15: A program to change the elements of a list.

                          Program15.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[:])

                       116  Premium Edition-VIII

| 113 114 115 116 117 118 119 120 121 122 123 |