mutating lists (class slides)

CSc 110 - mutating lists

Announcements

  • Midterm 3 November 20 (Wednesday) bring photo ID
  • Review session November 19, 5pm to 7pm at Gittings 129b

Lists are mutable

  • changes to a list in a function will remain after the function finishes running
  • changes to individual list elements do not change the list itself

Removing elements from a list in a loop

Using a for i in range when removing items in a list throws an error

numbers = [1, 2, 1, 4, 5]
for i in range(len(numbers)):
  numbers.pop(i)
numbers

ERROR

Removing elements from a list in a loop

Use a while loop instead (remember to adjust i if doing conditional removal)

numbers = [1, 2, 1, 4, 5]
i = 0
while i < len(numbers):
  numbers.pop(i)
numbers
[]

Or go backwards

numbers = [1, 2, 1, 4, 5]
for i in range(len(numbers)-1, -1, -1):
  numbers.pop(i)
numbers
[]

Write a function

Write a function called remove_names that takes one argument: a list of strings. The function should mutate and return the argument list removing all strings that end in vowel from that list.

Name your file delete_from_list.py and submit it for attendance on gradescope.

names = ["Beatrice", "Philip", "Anna", "Peter"]
remove_names(names)
assert names == ["Philip", "Peter"]

Write a function – solution

def remove_names(string_list):
  i = 0
  while i < len(string_list):
    if string_list[i][-1] in "aeiou":
      string_list.pop(i)
    else:
      i += 1
  return string_list
      
def main():
  names = ["Beatrice", "Philip", "Anna", "Peter"]
  remove_names(names)
  assert names == ["Philip", "Peter"]
  print(names) # ["Philip", "Peter"]

main()
['Philip', 'Peter']

Removing elements from inner lists in 2D lists

lists_of_numbers = [ [2, 3, 1, 2], [4, 5, 2, 1] ]
for inner_list in lists_of_numbers:
  for i in range(len(inner_list)-1, -1, -1):
    inner_list.pop(i)
    
print(lists_of_numbers)
[[], []]

Write a function

  1. Its name is remove_odds
  2. It takes a list of lists of integers as argument
  3. It mutates the inner list, removing odd numbers
lists_of_numbers = [ [2, 3, 1, 2], [4, 5, 2, 1] ]
remove_odds(lists_of_numbers)
assert lists_of_numbers == [ [2, 2], [4, 2] ]

Write a function – solution

def remove_odds(lists_of_numbers):
  for inner_list in lists_of_numbers:
    for i in range(len(inner_list)-1, -1, -1):
      if inner_list[i] % 2 != 0:
        inner_list.pop(i)
  return lists_of_numbers

def main():
  test_list = [ [2, 3, 1, 2], [4, 5, 2, 1] ]
  remove_odds(test_list)
  assert test_list == [ [2, 2], [4, 2] ]
  print(test_list) # [ [2, 2], [4, 2] ]
  
main()
[[2, 2], [4, 2]]