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.

Activity: CodeLens 17.4.2 (clens17_4_1)

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.

You have attempted of activities on this page