[Tutor] Acting on objects in a list - how to make the change permanent?

Chad Crabtree flaxeater at yahoo.com
Tue Sep 28 06:25:02 CEST 2004


Kent Johnson wrote:

> Adam,
>
> You are confusing a "list of things that should be deleted" with
the 
> list from which they should be deleted.
>
> For example suppose I have the list [1, 2, 3, 4, 5]:
> >>> a=[1, 2, 3, 4, 5]
> >>> a
> [1, 2, 3, 4, 5]
>
> Now I get a list of things to delete from a:
> >>> d=[1, 3]
>
> Deleting something from d will not be helpful!
> >>> d.remove(1)
> >>> a
> [1, 2, 3, 4, 5]
> >>> d
> [3]
>
> I have to remove from a:
> >>> d=[1, 3]
> >>> for i in d:
> ...   a.remove(i)
> ...
> >>> d
> [1, 3]
> >>> a
> [2, 4, 5]
>
> OK, now in your real code, you have a nested structure of lists - a

> magazine collection has titles which have issues which have
articles. 
> So it's not so simple, when you have just the list d, to figure out

> what list to delete from - it could be any of the issues in any of
the 
> titles.
>
> The solution is to remember which list the item to be deleted
occurs 
> in. Say we have two lists:
> >>> a=[1, 2, 3, 4, 5]
> >>> b=[3, 4, 5, 6]
>
> If I tell you to remove item 3, what will you do? But if I tell you
to 
> remove item 3 from list b, you know what to do. So the list of
things 
> to delete has to include information about the list to delete from.

> Say we want to remove 3 from b and 4 from a:
> >>> d=[ (3, b), (4, a) ]
>
> Now d is a list of tuples. Each tuple tells me an item to delete
from 
> a specific list. Here's how to remove them:
> >>> for val, lst in d:
> ...   lst.remove(val)
> ...
> >>> a
> [1, 2, 3, 5]
> >>> b
> [4, 5, 6]
>
I like this however if you use remove it only removes the first value
of 
that not an index.   If you have duplicate values then this may not
work 
this is how I normally remove certain items from a list.

 >>> a=range(10)
 >>> b=[]
 >>> for index,value in enumerate(a):
    if value%2==0:
        b.append(index)      
 >>> b
[0, 2, 4, 6, 8]
 >>> b.reverse()
 >>> for x in b:
    del a[x]
 >>> a
[1, 3, 5, 7, 9]
 >>>

I reverse b because it holds the values of indexes that I need, if I 
delete them in the orignal order than I will get out of index errors
(I 
know from experience) so when deleting a series from lists do it from

back to front.  Just another way.




		
__________________________________
Do you Yahoo!?
Yahoo! Mail is new and improved - Check it out!
http://promotions.yahoo.com/new_mail


More information about the Tutor mailing list