Shi Mu wrote: > In the follwoing code, > Why the result is "'defenestrate', 'window', 'defenestrate', " before > the original list instead of 'defenestrate', 'window', ? > > >>>>a = ['defenestrate', 'cat', 'window', 'defenestrate'] >>>>for x in a[:]: > > ... if len(x) > 4: a.insert(0, x) > ... > >>>>a > > ['defenestrate', 'window', 'defenestrate', 'defenestrate', 'cat', > 'window', 'defenestrate'] > The loop cycles over a *copy* of the list (that's what a[:] is, though list(a) would also work), and adds any items it finds whose length is greater that 4 at the start of the list, which starts out with four elements in it.
So it adds "defenestrate" the first time through the loop, nothing the second ("cat" is only three characters long), "window" the third and "defenestrate" the fourth. You can do a lot of this kind of playing at the interactive prompt, which will answer your questions much more quickly! For example, run the code with a could of print statements inserted: >>> a = ['one111', 'two', 'three', 'four'] >>> for x in a[:]: ... print "x:", x ... if len(x) > 4: a.insert(0, x) ... print a ... x: one111 ['one111', 'one111', 'two', 'three', 'four'] x: two ['one111', 'one111', 'two', 'three', 'four'] x: three ['three', 'one111', 'one111', 'two', 'three', 'four'] x: four ['three', 'one111', 'one111', 'two', 'three', 'four'] >>> regards Steve > On 10/25/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > >>Shi Mu wrote: >> [about list comprehensions, explained by Fredrik] -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list