# python迭代列表时如果要修改之,需先复制 原

好铁

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

for 语句中nums如果不加[:], 结果就会出问题.

stackoverflow上有个相关回答:

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.

For example (depends on what type of list):

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

An example:

``````>>> 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

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:

``````>>> 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']``````

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.,

``````for x in a[:]:
if x < 0: a.remove(x)``````

### 好铁

Python 3 入门，最全面的基础看这篇就够了！

09/02
0
0

justjavac
2013/03/12
308
1

2017/12/26
0
0
Python知识点总结篇（二）

10/03
0
0
python基础（5）：深入理解 python 中的赋值、引用、拷贝、作用域

2013/07/21
0
8

stylus

stylus基础教程,stylus实例教程,stylus语法总结

miaojiangmin
38分钟前
3
0
PHP生成CSV之内部换行

2
0

8
0

5
0
JAVA-四元数类

public class Quaternion { private final double x0, x1, x2, x3; // 四元数构造函数 public Quaternion(double x0, double x1, double x2, double x3) { this.x0 = ......

Pulsar-V

20
0