17.4. Nested IterationΒΆ

When you have nested data structures, especially lists and/or dictionaries, you will frequently need nested for loops to traverse them.

Line 3 executes once for each top-level list, three times in all. With each sub-list, line 5 executes once for each item in the sub-list. Try stepping through it in Codelens to make sure you understand what the nested iteration does.

(clens17_4_1)

Check Your Understanding

        nested-3-1: Now try rearranging these code fragments to make a function that counts all the *leaf* items in a nested list like nested1 above, the items at the lowest level of nesting (8 of them in nested1).def count_leaves(n):
---
    count = 0
---
    for L in n:
---
        for x in L:
---
            count = count + 1
---
    return count
        
2. Below, we have provided a list of lists that contain information about people. Write code to create a new list that contains every person’s last name, and save that list as last_names.
3. Below, we have provided a list of lists named L. Use nested iteration to save every string containing β€œb” into a new list named b_strings.
Next Section - 17.5. πŸ‘©β€πŸ’» Structuring Nested Data