Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a and a[:] in a loop

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 ?

like image 388
Hirak Sarkar Avatar asked May 05 '26 21:05

Hirak Sarkar


1 Answers

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.

like image 110
BrenBarn Avatar answered May 07 '26 09:05

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!