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.
Check Your Understanding
: 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
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