Different ways of Iterating over a list

爷,独闯天下 提交于 2019-12-20 01:59:19

问题


Can somebody tell me what's the difference between this code:

x = [1, 2, 3, 4, 5, 6, 7]
for i in x[:]:
    if i == 5:
        x.insert(0, i)

And this code:

x = [1, 2, 3, 4, 5, 6, 7]
for i in x:
    if i == 5:
        x.insert(0, i)

Why doesn't the second one work? I know it is mentioned in the Python tutorial, but I can't quite understand it.


回答1:


In the first version, you create a copy (by slicing the list from the beginning to the end), in the second one you're iterating over the original list.

If you iterate over a container, its size can't change during iteration, for good reasons (see below). But since you call x.insert, the size of your list changes.


If you execute the second version, it actually doesn't throw an error immediately, but continues indefinitely, filling the list up with more and more 5s:

Once you're at the list index 4 (and i is therefore 5), you're inserting a 5 at the beginning of the list:

[5, 1, 2, 3, 4, 5, 6, 7]

You then continue in the loop, implicitly increasing your index to 5, which is now again 5, because the whole list got shifted one to the right, due to your insertion, so 5 will be inserted again:

[5, 5, 1, 2, 3, 4, 5, 6, 7]

This goes on "forever" (until there's a MemoryError).



来源:https://stackoverflow.com/questions/35206863/different-ways-of-iterating-over-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!