Page 45 -
P. 45

meet python


           Lists are like arrays


           When you create a list in Python, the interpreter creates an array-like data
           structure in memory to hold your data, with your data items stacked from
           the bottom up. Like array technology in other programming languages, the
           first slot in the stack is numbered 0, the second is numbered 1, the third is
           numbered 2, and so on:
       This is your
       “movies” list in             Item #0                   Item #1                   Item #2
        code.

                   movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"]




                       This is your “movies”
                       list in memory.                                        2

                                               "The Meaning of Life"
                                                                                            Each data item
                                                                                            in the list has a
                                                                             1              numeric OFFSET
                                                "The Life of Brian"
                                                                                            associated with it.

                                                                               0
                                                  "The Holy Grail"

                                                                            Python starts counting
                                                                            from zero.
           Access list data using the square bracket notation

          As with arrays, you can access the data item in a list slot using the standard
           square bracket offset notation:




                print(movies[1])                        The Life of Brian


          Use the “print()” BIF to display a                No surprise here, really…the
           data item on screen.                             requested data appears on screen.



           Let’s use IDLE to learn a bit about how lists work.

                                                                                        you are here 4    9
   40   41   42   43   44   45   46   47   48   49   50