On Wed, 30 Jan 2008 23:49:46 -0800, [EMAIL PROTECTED] wrote: > I supposed the below code will print seven 2 and generate the list li > without 2. > Strangely it only print four 2. If you change the number of 2 in the > list, the results are all beyond expectation. I know the other way to > achieve the expected goal, but why this is happening? Could somebody > enlight me?
Do not modify a list at the same time that you are traversing it. If you look at the archives (say, on Google Groups, or any number of other places), this topic was just discussed yesterday and earlier today. See the thread with subject line: "Removal of element from list while traversing causes the next element to be skipped" As for why it is happening... you have code that looks like this: for x in li: if x == 2: print x li.remove(x) Consider that "under the hood", the for-loop looks something like this: i = 0 while i < the length of the list: set x equal to the item in the i-th position execute the loop block of code i += 1 If you start deleting or inserting items in the middle of the loop, the index won't be pointing where you expect. -- Steven -- http://mail.python.org/mailman/listinfo/python-list