Page 51 -
P. 51

meet python


           Work with your list data


           You often need to iterate over your list and perform some action on each item
           as you go along. Of course, it is always possible to do something like this,
                                                                                     Define a list and populate its
           which works but does not scale:
                                                                                     items with the names of two
                                                                                    movies.
                                   fav_movies = ["The Holy Grail", "The Life of Brian"]


                                   print(fav_movies[0])      This is the list-processing
             Display the value of    print(fav_movies[1])     code.
              each individual list item
              on the screen.


           This code works as expected, making the data from the list appear on screen.
           However, if the code is later amended to add another favorite movie to the list,
           the list-processing code stops working as expected, because the list-processing code
           does not mention the third item.

           Big deal: all you need to do is add another print() statement, right?
           Yes, adding one extra print() statement works for one extra movie, but
           what if you need to add another hundred favorite movies? The scale of the
           problem defeats you, because adding all those extra print() statements
           becomes such a chore that you would rather find an excuse not to have to do.


           It’s time to iterate

           Processing every list item is such a common requirement that Python makes it
           especially convenient, with the built-in for loop. Consider this code, which is
           a rewrite of the previous code to use a for loop:
                                                                                    Define a list and populate it
                                                                                    just as you did before.
          Use “for” to iterate
          over the list, displaying
           the value of each    fav_movies = ["The Holy Grail", "The Life of Brian"]
           individual item on
           screen as you go.   for each_flick in fav_movies:        This is the list-processing


                                     print(each_flick)               code, using a for loop.




           Using a for loop scales and works with any size list.

                                                                                       you are here 4    15
   46   47   48   49   50   51   52   53   54   55   56