Page 52 -
P. 52

list processing


           For loops work with lists of any size


           Python’s for loop exists to process lists and other iterations in Python. Lists are
           the most common iterated data structure in Python, and when you need to
           iterate a list, it’s best to use for:
         The keyword “for”                               The keyword “in” separates      A colon “:” follows your
         indicates the start                              the target identifier from     list name and indicates
          of the loop and                                 your list.                     the start of your list-
          comes before the                                                               processing code.
          target identifier.
                         for         in     :
                                       target identifer
                                                                            list





                                                list-processing code

                   The list-processing code
                   MUST be indented
                    under the for loop.


           The list-processing code is referred to by Python programmers as the suite.
           The target identifier is like any other name in your code. As your list is
           iterated over, the target identifier is assigned each of the data values in your
           list, in turn. This means that each time the loop code executes, the target
           identifier refers to a different data value. The loop keeps iterating until it
           exhausts all of your list’s data, no matter how big or small your list is.
           An alternative to using for is to code the iteration with a while loop.
           Consider these two snippets of Python code, which perform the same action:
         When you use “while”,
         you have to worry about
         “state information,”    count = 0
         which requires you     while count < len(movies):                  for each_item in movies:
         to employ a counting         print(movies[count])                        print(each_item)
          identifier.                 count = count+1


                                                                                   When you use “for”, the
                                                                                  Python interpreter
                                                                                  worries about the “state
           These while and for statements do the same thing.                      information” for you.



           16    Chapter 1
   47   48   49   50   51   52   53   54   55   56   57