Remove elements as you traverse a list in Python [duplicate]

爱⌒轻易说出口 提交于 2019-11-28 07:01:28

Iterate over a copy of the list:

for c in colors[:]:
    if c == 'green':
        colors.remove(c)

Best approach in Python is to make a new list, ideally in a listcomp, setting it as the [:] of the old one, e.g.:

colors[:] = [c for c in colors if c != 'green']

NOT colors = as some answers may suggest -- that only rebinds the name and will eventually leave some references to the old "body" dangling; colors[:] = is MUCH better on all counts;-).

You could use filter function:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>

or you also can do like this

>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
...     colors.remove('green')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!