python迭代列表時若是要修改之,需先複製

刷leetcode時, 有個移除元素的題 html

def removeElement(self, nums, val):
        for x in nums[:]:
            if x == val:
                nums.remove(val)
        return len(nums)



for 語句中nums若是不加[:], 結果就會出問題.



stackoverflow上有個相關回答: python

You need to take a copy of the list and iterate over it first, or the iteration will fail with what may be unexpected results. ide

For example (depends on what type of list): oop

for tup in somelist[:]:
    etc....

An example: ui

>>> somelist = range(10)
>>> for x in somelist:
...     somelist.remove(x)
>>> somelist
[1, 3, 5, 7, 9]

>>> somelist = range(10)
>>> for x in somelist[:]:
...     somelist.remove(x)
>>> somelist
[]
the second one iterates over a copy of the list. So when you modify the original list, you do not modify the copy that you iterate over




官網tutorial中也給出了例子: this

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient: spa

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']


還有下面這個note code

There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g., htm

for x in a[:]:
    if x < 0: a.remove(x)
相關文章
相關標籤/搜索