On 13 June 2015 at 08:17, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > On Sat, 13 Jun 2015 13:32:59 +0800, jimages wrote: > >> I am a newbie. I also have been confused when I read the tutorial. It >> recommends make a copy before looping. Then I try. >> #-------------------------- >> Test = [1, 2] >> For i in Test: >> Test.append(i) >> #-------------------------- > > You don't make a copy of Test here. You could try this instead: > > Test = [1, 2] > copy_test = Test[:] # [:] makes a slice copy of the whole list > for i in copy_test: # iterate over the copy > Test.append(i) # and append to the original > > print(Test) > > > But an easier way is: > > Test = [1, 2] > Test.extend(Test) > print(Test)
I can't see anything in the docs that specify the behaviour that occurs here. If I change it to Test.extend(iter(Test)) then it borks my system in 1s after consuming 8GB of RAM (I recovered with killall python in the tty). According to the docs: """ list.extend(L) Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L. """ https://docs.python.org/2/tutorial/datastructures.html#more-on-lists The alternate form Test[len(Test):] = Test is equivalent but Test[len(Test):] = iter(Test) is not since it doesn't bork my system. I looked here: https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types but I don't see anything that specifies how self-referential slice assignment should behave. I checked under pypy and all behaviour is the same but I'm not sure if this shouldn't be considered implementation-defined or undefined behaviour. It's not hard to see how a rearrangement of the list.extend method would lead to a change of behaviour and I can't see that the current behaviour is really guaranteed by the language and in fact it's inconsistent with the docs for list.extend. As an aside they say that pypy is fast but it took about 10 times longer than cpython to bork my system. :) -- Oscar -- https://mail.python.org/mailman/listinfo/python-list