Coding problem for removing odd number


#1

image
my code as below
but the hint said it failed to remove 2x 5 in list[4,5,5,2], the result is [4,5,2]
can someone tell me why and how to modify it?
thks.
################################
def purify(collect):
for i in collect:
if i % 2 != 0:
collect.remove(i)
return collect
###############################


#2

well, lists can’t have empty indexes so if you have [4, 5, 5, 2] and you do .remove(5), remove() will remove the first match it can find. so then we get:

a_list = [4, 5, 5, 2]
a_list.remove(5)
print a_list # [4, 5, 2]

everything to the right of the removed item shifts one index to the left. This is where your problem comes from, because this index shifts occurs, while the loop moves on to the next index. Causing a successive odd number to be skipped.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.