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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With