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

Adam Cripps kabads at gmail.com
Mon Sep 27 22:36:16 CEST 2004


On 27 Sep 2004 16:05:09 -0400, Lloyd Kvam <pythontutor at venix.com> wrote:
> 
> 
> 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


Hrmm - this kind of brings me full-circle, as that was the command
that I originally tried and it doesn't seem to change the object. When
I go through and look at the object again, it's still there. I don't
get any errors with this either.  I don't return the list, so I'm not
sure if the object is being returned. Here's the small piece of code
that I'm working with:

for i in returned_list:
    if intchoice == iter_count:
        action = raw_input ("""Would you like to delete this object?  (y/n)""") 
        if action == "y":
            intchoice = intchoice -1 # First one is zero - need to take one off	
            del returned_list[intchoice]
            print "deleted"
            return # Do I need to return the new list?
    else:
        print "You chose not to delete"
        return
    iter_count = iter_count + 1	# This goes through the loop

Does this shed any light on what I'm trying to do? 

Adam


More information about the Tutor mailing list