Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #27113

Re: A difficulty with lists

From Madison May <worldpeaceagentforchange@gmail.com>
Newsgroups comp.lang.python
Subject Re: A difficulty with lists
Date 2012-08-15 14:12 -0700
Organization http://groups.google.com
Message-ID <16702a22-6ce3-4120-bbcc-9649e1717130@googlegroups.com> (permalink)
References <jvp75j$opr$1@news.albasani.net>

Show all headers | View raw


On Monday, August 6, 2012 3:50:13 PM UTC-4, Mok-Kong Shen wrote:
> I ran the following code:
> 
> 
> 
> def xx(nlist):
> 
>    print("begin: ",nlist)
> 
>    nlist+=[999]
> 
>    print("middle:",nlist)
> 
>    nlist=nlist[:-1]
> 
>    print("final: ",nlist)
> 
> 
> 
> u=[1,2,3,4]
> 
> print(u)
> 
> xx(u)
> 
> print(u)
> 
> 
> 
> and obtained the following result:
> 
> 
> 
> [1, 2, 3, 4]
> 
> begin:  [1, 2, 3, 4]
> 
> middle: [1, 2, 3, 4, 999]
> 
> final:  [1, 2, 3, 4]
> 
> [1, 2, 3, 4, 999]
> 
> 
> 
> As beginner I couldn't understand why the last line wasn't [1, 2, 3, 4].
> 
> Could someone kindly help?
> 
> 
> 
> M. K. Shen

The list nlist inside of function xx is not the same as the variable u outside of the function:  nlist and u refer to two separate list objects.  When you modify nlist, you are not modifying u.  If you wanted the last line to be [1, 2, 3, 4], you could use the code below:

#BEGIN CODE

def xx(nlist):
 
    print("begin: ",nlist)
 
    nlist+=[999]
 
    print("middle:",nlist)
 
    nlist=nlist[:-1]
 
    print("final: ",nlist)
 
    return nlist
 
u=[1,2,3,4]
 
print(u)
 
u = xx(u)
 
print(u)

#END CODE


Notice that I changed two things.  First, the function xx(nlist) returns nlist.  Secondly, u is reassigned to the result of xx(nlist).

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

A difficulty with lists Mok-Kong Shen <mok-kong.shen@t-online.de> - 2012-08-06 21:50 +0200
  Re: A difficulty with lists MRAB <python@mrabarnett.plus.com> - 2012-08-06 21:19 +0100
  Re: A difficulty with lists Madison May <worldpeaceagentforchange@gmail.com> - 2012-08-15 14:12 -0700
    Re: A difficulty with lists Terry Reedy <tjreedy@udel.edu> - 2012-08-15 20:21 -0400
      Re: A difficulty with lists Madison May <worldpeaceagentforchange@gmail.com> - 2012-08-16 06:46 -0700
  Re: A difficulty with lists Madison May <worldpeaceagentforchange@gmail.com> - 2012-08-15 16:56 -0700
  Re: A difficulty with lists Cheng <chbeh88@googlemail.com> - 2012-08-20 13:43 -0700

csiph-web