nested for loops (slides)

CSc 110 - nested for loops

2D lists

people = [["Ana", 34, "B"],
          ["Peter", 23, "A"]]

How to retrieve first name "Ana"?

How to retrieve first name "Peter"?

How to retrieve integer 23?

2D lists

people = [["Ana", 34, "B"],
          ["Peter", 23, "A"]]

How to retrieve first name "Ana"?

people[0][0]
'Ana'

How to retrieve first name "Peter"?

people[1][0]
'Peter'

How to retrieve integer 23?

people[1][1]
23

Nested for loops

people = [["Ana", 34, "B"],
          ["Peter", 23, "A"]]
          
for i in range(len(people)):
  for j in range(len(people[i])):
    print(people[i][j])
Ana
34
B
Peter
23
A

Write a function

It returns the highest value among all the numbers in the list.

Test cases

assert nested_max([[], []]) == None
assert nested_max([[1, 2, 3, 2, 1],
                   [2, 3, 2, 1, 5],
                   [0, 1]]) == 5

Write a function – solution

def nested_max(lists):
  max = None
  for i in range(len(lists)):
    for j in range(len(lists[i])):
      if max == None or lists[i][j] > max:
        max = lists[i][j]
  return max

def main():
  assert nested_max([[], []]) == None
  assert nested_max([[1, 2, 3, 2, 1],
                     [2, 3, 2, 1, 5],
                     [0, 1]]) == 5
  print("Passed all tests")
main()
Passed all tests

Loop Table

def nested_max(lists):
  max = None
  for i in range(len(lists)):
    for j in range(len(lists[i])):
      if max == None or lists[i][j] > max:
        max = lists[i][j]
  return max

max_nested([[], [], [2, 1], [0, 5])

Draw a loop table with:

  • values of i, j,len(lists[i]), lists[i][j], and max for each nested loop iteration
  • Hint: both values of j and lists[i][j] are "-" if an inner list is empty

Loop Table – solution

max_nested([[], [], [2, 1], [0, 5])
ijlen(lists[i])lists[i][j]max
0-0-None
1-0-None
20222
21212
30202
31255

Read solution: correct or not?

def max_list(numbers):
  max = None
  for n in numbers:
    if max == None or n > max:
      max = n
  return max

def nested_max(lists):
  max = None
  for i in range(len(lists)):
    max_of_sublist = max_list(lists[i])
    if max == None or  max_of_sublist > max:
      max = max_of_sublist
  return max

def main():
  assert nested_max([[1, 2, 3, 2, 1],
                     [],
                     [5, 1]]) == 5

main()

Write a function

It returns the lowest number in all inner lists.

Test cases:

assert nested_min([[], []]) == None
assert nested_min([[1, 2, 3, 2, 1],
                   [2, 3, 2, 1, 5],
                   [0, 1]]) == 0

Write a function – solution

def nested_min(lists):
  min = None
  for i in range(len(lists)):
    for j in range(len(lists[i])):
      if min == None or lists[i][j] < min:
        min = lists[i][j]
  return min

def main():
  assert nested_min([[], []]) == None
  assert nested_min([[1, 2, 3, 2, 1],
                     [2, 3, 2, 1, 5],
                     [0, 1]]) == 0
  print("Passed all tests")
main()
Passed all tests

Quiz 09

current time

You have 10 minutes to complete the quiz.

Mutate nested lists

In addition to retrieving a value from nested lists, we can also mutate a value in a sublist.

people = [["Ana", 24, "B"],
          ["Peter", 23, "A"]]
people
[['Ana', 24, 'B'], ['Peter', 23, 'A']]
people[0][1] = 54
people
[['Ana', 54, 'B'], ['Peter', 23, 'A']]

Write a function

It mutates the sublist items by multiplying each number in each sublist by 2 and returns the argument list.

Test cases

assert double_nested([[], []]) == [[], []]
assert double_nested([[1, 2, 3, 2, 1],
                     [0, 1]]) == [[2, 4, 6, 4, 2],
                                  [0, 2]]

Write a function – solution

def double_nested(lists):
  for i in range(len(lists)):
    for j in range(len(lists[i])):
      lists[i][j] *= 2
  return lists

def main():
  assert double_nested([[], []]) == [[], []]
  assert double_nested([[1, 2, 3, 2, 1],
                        [0, 1]]) == [[2, 4, 6, 4, 2],
                                     [0, 2]]
  print("Passed all tests")
main()
Passed all tests

Write a function

It mutates the sublist items by reversing each string (use string[::-1] to reverse it) and returns the argument list.

Name file reverse_strings.py and submit your attendance.

Test cases:

assert reverse_strings_nested([["desserts", "raw", "live"],
                               ["smart", "knits"]]) == [["stressed", "war", "evil"],
                                                        ["trams", "stink"]]

Write a function – solution

def reverse_strings_nested(strings):
  for i in range(len(strings)):
    for j in range(len(strings[i])):
      strings[i][j] = strings[i][j][::-1]
  return strings

def main():
  original_strings = [["desserts", "raw", "live"],
                      ["smart", "knits"]]
  reverse_strings_nested(original_strings)   
  assert  original_strings == [["stressed", "war", "evil"],
                               ["trams", "stink"]]
  
  print(original_strings)
  
main()
[['stressed', 'war', 'evil'], ['trams', 'stink']]