Page 64 -
P. 64

reduce, reuse, recycle


           Don’t repeat code; create a function


           Take a look at the code that you’ve created so far, which (in an effort to save
           you from having your brain explode) has already been amended to process yet
           another nested list. Notice anything?
                                     This code is essentially the
                                     same as this code…


              for each_item in movies:                                         …which is essentially
                     if isinstance(each_item, list):                            the same as this
                           for nested_item in each_item:                        code…
                                  if isinstance(nested_item, list):
                                                                                                    …which is not
                                         for deeper_item in nested_item:                            that much
                                                if isinstance(deeper_item, list):                   different than
                                                       for deepest_item in deeper_item:             this code.
                                                              print(deepest_item)
                                                else:
                                                       print(deeper_item)
                                 else:
                                         print(nested_item)              There’s not much
                                                                          four statements, either!
                     else:                                                difference among these
                           print(each_item)



                                                       This code is beginning to get a little scary…


          Your code now contains a lot of repeated code. It’s also a mess to look at, even
           though it works with the movie buff’s amended data. All that nesting of for
           loops is hard to read, and it’s even harder to ensure that the else suites are
           associated with the correct if statement.

           There has to be a better way…but what to do?
           When code repeats in this way, most programmers look for a way to take
           the general pattern of the code and turn it into a reusable function. And
           Python programmers think this way, too. Creating a reusable function lets
           you invoke the function as needed, as opposed to cutting and pasting existing
           code.

           So, let’s turn the repeating code into a function.


           28    Chapter 1
   59   60   61   62   63   64   65   66   67   68   69