Confused over Lists

Harvey Thomas hst at empolis.co.uk
Fri Aug 2 10:15:26 EDT 2002


Paul Brian [mailto:paul1brian at yahoo.com] wrote
> 
> Dear all,
> 
> If I have a list of items, and wish to test each item, and 
> remove those
> items that meet a certain criteria, I assumed I could use 
> list.remove()
> 
> however I came across the following problem:
> 
> imagine a list of numbers, [1,1,2,3,4,5] and I wish to remove 
> all the 1's.
> 
> the following I thought should work :-
> 
> demoList = [1, 1, 2, 3, 4, 5]
> for num in demoList:
>     if num == 1:
>         demoList.remove(num)
> print demoList
> 
> but I get
> >>> [1, 2, 3, 4, 5]
> 
> 
> There appears to be a magic counter that keeps track of what 
> index it has
> already iteratered over in the list.
> When the first "1" is encountered (index 0) it removes it, 
> and shifts the
> next "1" to index 0.
> But the magic counter thinks it has already visited index 0 
> and so "blips"
> over the second 1, thus not removing that "1" from the list.
> 
> Now this does make sense, and I can get round it using 
> seperate lists as
> stores, but 2 questions
> 
> 1) Am I missing something really obvious on how to handle 
> this the way I
> think it *should* work (NB absolutley no PEP orientated 
> issues here - no
> desire to try and say we should change behaviour of lists cos 
> i dont get it)
> 
> 2) How do I get access to that magic counter. It would be 
> very useful in all
> sorts of ways.
> 
> Thank you :-)
> 
> 
> 
> ------------------------------
> Paul Brian
> (07899) 877 295
> paul1brian at yahoo.com

To answer your first question:

filter(lambda x: x!= 1, demoList)

will give you a new list with the 1 elements removed

HTH

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.




More information about the Python-list mailing list