Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 139 - 2609_Logicode
P. 139

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

                     Program 12: To create a nested list

                         Program12.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 13: To access the different elements of a list

                         Program13.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])

                     You will get the following output:

                         Output
                      3
                      Computer
                      40

                     LIST FUNCTIONS

                     Let us study some of the functions we can use with lists.

                     The append() Function
                     The  append() function  inserts  the  object  passed  to  it  at  the  end  of the  list.  Syntax  of using
                     append() function is:

                         list_name.append(item)

                                                                                               String and List in Python  137

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