[1, 2, 1, 4, 5]
Changes to individual list elements do not change the list itself
Use a for i in range
loop instead:
It takes a 2D list of integers as argument with at least one inner list. It mutates the list, replace each inner list with a tuple. The tuple is the total and mean of that inner list.
line 2: can we use for sublist in lists
?
line 7: can we use for n in lists[i]
?
def total_mean(lists):
for i in range(len(lists)): #must use for i in range(len(lists))
total = None
mean = None
if len(lists[i]) > 0:
total = 0
for j in range(len(lists[i])): #can also use for n in lists[i]
total += lists[i][j]
mean = total/len(lists[i])
lists[i] = total, mean #need to use i to mutate lists
return lists
def main():
test_list = [[2, 4, 6, 8], [], [2, 3, 4]]
total_mean(test_list)
assert test_list == [(20, 5.0), (None, None), (9, 3.0)]
assert total_mean([[2, 4, 6, 8], [], [2, 3, 4]]) == [(20, 5.0), (None, None), (9, 3.0)]
main()
loop
for i in range
when removing list items throws an ERROR.
ERROR
loop
Visualize the execution in Python Tutor.
while
loop without adjusting i
for
loop but go backwardsremove_names
mutates
and returns
the argument list removing all strings that end in vowelName as delete_from_list.py
, submit to Gradescope.
remove_odds
def remove_odds(lists):
for i in range(len(lists)):
for j in range(len(lists[i])-1, -1, -1):
if lists[i][j] % 2 != 0:
lists[i].pop(j)
return lists
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]]
line 2: can we use for innerlist in lists
?
line 3: can we use for X in list
?
def remove_odds(lists):
for inner_list in lists: # yes we can
for i in range(len(inner_list)-1, -1, -1): # no
if inner_list[i] % 2 != 0:
inner_list.pop(i)
return lists
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]]
data.txt
code.py
def write_result(input_filename, output_filename):
data = open(input_filename, 'r')
result = open(output_filename, 'w')
for line in data:
words = line.strip().split(' ')
for w in words:
if w[0] == w[-1]:
result.write(w + '\n')
data.close()
result.close()
if __name__ == '__main__':
write_result('data.txt', 'result.txt')