Reputation: 519
The following code snippets generate different output in Python:
a = ['b','c']
for x in a:
a.insert(0,'d')
The loop does not terminate and the python shell hangs. While,
a = ['b','c']
for x in a[:]:
a.insert(0,'d')
print a
generates the following : ['d','d','b','c']
for python 2.6.6
Can anyone please explain the difference in above behavior ?
Upvotes: 3
Views: 359
Reputation: 251363
In the first example, you add to the list while you iterate over it. It never stops because you keep making the list longer as you go, so it can never get to the end.
In the second example a[:]
is a copy of the list. You can iterate over the copy while appending to the original just fine.
Upvotes: 15
Reputation: 250921
a[:]
is equivalent to list(a)
, so in the second loop you're looping over the shallow copy of a
and inserting to original a
. As the length of a[:]
is two therefore it inserts only two elements.
While in the first loop you're iterating over a
ans also inserting elements to a
so a
goes on increasing and loop never stops.
Upvotes: 2