loop
Using a for i in range
when removing items in a list throws an error
ERROR
loop
Use a while
loop instead (remember to adjust i
if doing conditional removal)
Or go backwards
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.
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']
remove_odds
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]]