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