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).
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
.