Page 56 -
P. 56

looking for lists


           Check a list for a list


           Each time you process an item in your list, you need to check to see if the
           item is another list. If the item is a list, you need to process the nested list
           before processing the next item in your outer list. Deciding what to do when in
           Python follows the familiar if... else... pattern:
                  The keyword “if”                                          A colon (:) follows your
                  indicates the start                                       condition test.
                  of the decision code.
                                   if           :
                                              some condition holds


                 This code executes if the               the "true" suite
                 condition holds (i.e., it’s TRUE).


                                   else:                Look! Another colon.                    Note: both suites
                                                                                                are indented.


              This code executes if the condition          the "false" suite
              does NOT hold (i.e., it’s FALSE).



           No surprises here, as the if statement in Python works pretty much as
           expected. But what condition do you need to check? You need a way to
           determine if the item currently being processed is a list. Luckily, Python ships
           with a BIF that can help here: isinstance().
           What’s cool about the isinstance() BIF is that it lets you check if a
           specific identifier holds data of a specific type:







               Create a short list and      Let’s use the IDLE shell to learn a little about how isinstance() works:
               assign it to an identifier.
                                          >>> names = ['Michael', 'Terry']
         Ask if “names” is a list (it is).  >>> isinstance(names, list)       Refer to a Python type
                Assign a number to an     True                                here. In this case, the type
                                          >>> num_names = len(names)
                identifier.               >>> isinstance(num_names, list)     is “list”.
              Ask if “num_names” is a     False
              list (it isn’t).


           20    Chapter 1
   51   52   53   54   55   56   57   58   59   60   61