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

Lloyd Kvam pythonTutor at venix.com
Mon Sep 27 22:05:09 CEST 2004


On Mon, 2004-09-27 at 15:53, Adam Cripps wrote:
> On 27 Sep 2004 11:19:57 -0400, Lloyd Kvam <pythontutor at venix.com> wrote:
> > 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.
> > Lloyd Kvam
> > Venix Corp
> > 
> 
> Thanks Lloyd - 
> 
> What would the syntax be for deleting an object from a list? 
> I've tried (with an error)
> returned_list = del returned_list [intchoice]
> 
> Is there some other syntax that I should be trying here? 

del is a statement so it can't be part of an assignment statement.  Use:

	del returned_list[intchoice]

which modifies the list "in place".  There is no need for the
assignment.


> 
> Thanks again. 
> 
> Adam
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list