Why does list.remove() not behave as one might expect?

后端 未结 3 751
温柔的废话
温柔的废话 2020-12-15 11:34
from pprint import *

sites = [[\'a\',\'b\',\'c\'],[\'d\',\'e\',\'f\'],[1,2,3]]

pprint(sites)

for site in sites:
        sites.remove(site)

pprint(sites)
<         


        
3条回答
  •  没有蜡笔的小新
    2020-12-15 12:21

    It's because you're modifying a list as you're iterating over it. You should never do that.

    For something like this, you should make a copy of the list and iterate over that.

    for site in sites[:]:
        sites.remove(site)
    

提交回复
热议问题