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

后端 未结 3 742
温柔的废话
温柔的废话 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:16

    Normally I would expect the iterator to bail out because of modifying the connected list. With a dictionary, this would happen at least.

    Why is the d, e, f stuff not removed? I can only guess: Probably the iterator has an internal counter (or is even only based on the "fallback iteration protocol" with getitem).

    I. e., the first item yielded is sites[0], i. e. ['a', 'b', 'c']. This is then removed from the list.

    The second one is sites[1] - which is [1, 2, 3] because the indexes have changed. This is removed as well.

    And the third would be sites[2] - but as this would be an index error, the iterator stops.

提交回复
热议问题