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

Adam Cripps kabads at gmail.com
Tue Sep 28 07:47:52 CEST 2004


On Mon, 27 Sep 2004 22:13:05 -0400, Kent Johnson
<kent_johnson at skillsoft.com> 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]
> 
> You need to do something like this. Your list of things to remove has to
> include a reference to the list from which to remove it.
> 
> Kent
> <snip>

Kent, 

What you're suggesting sounds like the kind of thing that was going on
in my head, without me being to articulate it - I knew I had the list,
but not how to refer it to all the other data, which is crucial.

Thanks for this excellent advice. I will try and build a function
which creates a whole collection of lists (should be three, nested
within one another) holding all the instances, which the user will
then choose through the items (through the hierarchy of nests) and
then delete one. Should that then delete the item?

Thanks again
Adam


More information about the Tutor mailing list