[Tutor] 2 problems in a small script

Alan Gauld alan.gauld at btinternet.com
Fri Oct 12 09:34:48 CEST 2007


"Dick Moores" <rdm at rcblue.com> wrote

> Well, if deleting from the same list I'm traversing is the problem,
> why doesn't inserting the line
> lstB = lstA
>
> and deleting from lstB clear it up? The output is exactly the same.

You are not copying the list you are just making a second name
refer to the same list. You need to make a new copy, as in:

lstB = lstA[:]   # a full slice creates a copy

But thats not an efficient approach if you have a big list, the
best route is to build a new list, preferably using a list
comprehension.

> I thank you for showing me another way to get the result I want, but
> first I want to know why my code didn't work.

The reason is as stated. Your solution didn't do what you thought it 
did :-)

The other way you can do it is to use a while loop:

n = 0
while n < len(myList):  #computed each time
     if some_test(myList[n]):
         del(myList[n])
     else:
          n += 1

Note we do not increment n when we delete an element.

I cover this in the branching topic of my tutorial in the section
Modifying collections from inside loops
HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list