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

Lloyd Kvam pythonTutor at venix.com
Mon Sep 27 17:19:57 CEST 2004


I did NOT read your source code, so this is simply a guess.   Assigning
a modified list to a name does NOT change the original list.  Here's a
simple example:

>>> def odd_only(numlist):
...     odds = [n for n in numlist if n%2]
...     numlist = odds
...     return odds
...
>>> numlist = range(10)
>>> odd_only(numlist)
[1, 3, 5, 7, 9]
>>> numlist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The original numlist is NOT modified by the assignment in odd_only.

Since you are passing lists between functions, I am guessing that
somewhere you have logic like the example above.  The simple fix here is
to do:
	numlist = odd_only(numlist)

Hope this helps.


On Mon, 2004-09-27 at 10:01, Adam Cripps wrote:
> My python project (http://savannah.nongnu.org/projects/newmag) is
> teaching me a fair bit about how to write python code. However, I'm
> still a long way away from being remotely good, as some of my recent
> posts have shown.
> 
> I'm working on deleting instance objects and I've created a list of
> objects which is then piped through a menu to allow the user to choose
> which one is deleted.
> 
> The basic structure of the code is this: 
> 
>  * choose_what_to_edit  - creates a list which calls return_object_list
>      * return_object_list - return_object_list  -chooses what level
> the user wants to select an object
>         * choosetitle - selects a title
>             * chooseissue - if necssary selects an issue from the selected title
>                * choosearticle - and if nescessary, selects an article
> from the selected issue.
> 
> Basically, from this code, I get a list, which has objects within it.
> If I alter the objects within this list, how do I make them permanent?
> I'm currently trying to delete an item/object of the list the command
> del returned_list[choice] - however, this doesn't seem to be a
> permanent change. For the full code listing, please see the CVS
> project page.
> 
> Am I right in thinking that the list of objects will be referenced
> through to the actual instances, and if so, why aren't they being
> deleted? I've read some of the python docs, but can't see the solution
> here and would appreciate a more informed/specialised approach.
> 
> TIA.
> Adam
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list