[1, 2, 1, 4, 5]
Changes to individual list elements do not change the list itself
Use a for i in range loop instead:
square_alln**2)loopUsing a for i in range when removing items in a list throws an error
ERROR
loopUse a while loop instead (remember to adjust i if doing conditional removal)
Or go backwards
remove_namesmutates and returns the argument list removing all strings that end in voweldef 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']
def remove_names(string_list):
for i in range(len(string_list)-1, -1, -1):
if string_list[i][-1] in "aeiou":
string_list.pop(i)
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_oddsdef 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]]
Submit your remove_odds functions to Gradescope for attendance.
Name your file remove_odds.py