Why does my code for removing the even numbers from the beginning of a list not work?

£可爱£侵袭症+ 提交于 2021-01-29 06:39:45

问题


def delete_starting_evens(lst):
  for i in lst:
    if i%2==0:
      lst.remove(i)
    else:
      break
  return lst

The given code produces unexpected results, but I'm not able to figure out from the output where the problem lies.


回答1:


That's because you're suppressing items of a list your for-loop is iterating on. Hence it suppresses half of your items. For instance if you call your function on list [2, 2, 4, 6, 1] it will delete the first 2 of your list then move to lst[1] which is 4 (after deletion of the first 2), delete this one then move to lst[2] which is now 1 and terminates. The resulting list will be [2, 6, 1]

It is very bad practice to modify the structure you are iterating on. Here you should prefer a while loop:

def delete_starting_evens(lst):
    while len(lst) > 0 and lst[0]%2==0:
        lst.remove(lst[0])
    return lst

l = [2, 2, 4, 6, 1]
delete_starting_evens(l)
print(l)



来源:https://stackoverflow.com/questions/63193121/why-does-my-code-for-removing-the-even-numbers-from-the-beginning-of-a-list-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!