Page 60 -
P. 60

nested lists


           Handle many levels of nested lists


           The data and your code are not in sync.
           The movie buff’s data is a list that contains a nested list that itself contains
           a nested list. The trouble is that your code knows only how to process a list
           nested inside an enclosing list.
           The solution, of course, is to add more code to handle the additionally nested list. By
           looking at the existing code, it’s easy to spot the code you need to repeat:





                                        for each_item in movies:
                                               if isinstance(each_item, list):
                        This code                    for nested_item in each_item:
                        processes a
                        nested list.                        print(nested_item)
                                               else:
                                                     print(each_item)



                                                                                 Here’s where the
                                                                                repeated code needs
           The next                                                             to go.
            iteration of your
            code looks like
            this.



              for each_item in movies:
                     if isinstance(each_item, list):
                                                                                     The repeated code
                           for nested_item in each_item:
                                                                                     replaces the “print()”
                                 if isinstance(nested_item, list):                   statement and introduces
            Note: in this
              code, each                for deeper_item in nested_item:              another target identifier

            “if” needs an                       print(deeper_item)                  called “deeper_item”.


              associated         else:

            “else”.
                                        print(nested_item)
                     else:
                           print(each_item)



           24    Chapter 1
   55   56   57   58   59   60   61   62   63   64   65