17.4 Nested Iteration
From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period2 exercises2 graded tests
17.4 Nested Iteration
Read first in the book: 17.3 Processing JSON results.
When you have nested data structures, especially lists and/or dictionaries, you will frequently need nested for loops to traverse them.
nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]
for x in nested1:
print("level1: ")
for y in x:
print(" level2: " + y)
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.
nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]
for x in nested1:
print("level1: ")
for y in x:
print(" level2: " + y)
Step through this code in the book.
Check Your Understanding
Check your understanding: a mixed-up code puzzle in the book.
Exercise 1
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.
Open the
01folder and editmain.py. Run Tests checks it.
Exercise 2
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.
Open the
02folder and editmain.py. Run Tests checks it.
For teachers
17.4 Nested Iteration
Students read Foundations of Python Programming's “Nested Iteration” in CS Room and work through its 2 Python coding exercises (2 graded).
- Time: 1 class period
- Tests: 2 in 2 graded exercises, set up for you when you import the lesson
Reading first
Exercises
| Folder | Grading | Tests |
|---|---|---|
01 | Autograded | 1 |
02 | Autograded | 1 |