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.

(nested_data_11)

        exceptions-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
        
Next Section - Extracting from Nested Data