nested for loops (class 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

  1. Function name is nested_max
  2. It takes a 2D list of numbers as argument
  3. It iterates over every item in each sublist to find the highest number
  4. It returns the highest number in all lists

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 1

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

Write a function – solution 2

def max_list(numbers):
  max = None
  for i in range(len(numbers)):
    if max == None or numbers[i] > max:
      max = numbers[i]
  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([[], []]) == 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

Submit code for attendance

Submit your nested_max functions to Gradescope for attendance.

Name your file nested_max.py

Write a function

  1. Function name is nested_min
  2. It takes a 2D list of numbers as argument
  3. It iterates over every item in each sublist to find the lowest number
  4. It returns the lowest number in all 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

Mutate nested lists

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

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

Write a function

  1. Function name is double_nested
  2. It takes a 2D list of numbers as argument
  3. It mutates the sublist items by multiplying each number in each sublist by 2
  4. It 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

  1. Function name is len_strings_nested
  2. It takes a 2D list of strings as argument
  3. It mutates the sublist items by replacing each string with its length
  4. It returns the argument list

Test cases:

assert len_strings_nested([["desserts", "raw", "live"],
                            ["smart", "knits"]]) == [[8, 3, 4], [5, 5]]

Write a function – solution

def len_strings_nested(strings):
  for i in range(len(strings)):
    for j in range(len(strings[i])):
      strings[i][j] = len(strings[i][j])
  return strings

def main():
  original_list = [["desserts", "raw", "live"],
                               ["smart", "knits"]]
  assert len_strings_nested(original_list) == [[8, 3, 4], [5, 5]]
  print(original_list)
  
main()
[[8, 3, 4], [5, 5]]

Write a function

  1. Function name is reverse_strings_nested
  2. It takes a 2D list of strings as argument
  3. It mutates the sublist items by reversing each string (you can use string[::-1] to reverse it)
  4. It returns the argument list

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)
  print("Passed test")
  
main()
[['stressed', 'war', 'evil'], ['trams', 'stink']]
Passed test

Extra Activity – 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, 2], [3]])

Draw a loop table with:

  • value of max before loop, and in each iteration of the nested loops
  • values of i, j, and lists[i][j] for each nested loop iteration

Loop table – solution part 1

ijlen(lists[i])lists[i][j]max
0-0-None
1-0-None
20222
21212
30302
31355
32325

Loop table – solution part 2

ijlen(lists[i])lists[i][j]max
40135