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


Groups > comp.lang.python > #27530

Re: A difficulty with lists

From Cheng <chbeh88@googlemail.com>
Newsgroups comp.lang.python
Subject Re: A difficulty with lists
Date 2012-08-20 13:43 -0700
Organization http://groups.google.com
Message-ID <66aafdc3-7ea5-4401-859b-89cd5bf268a8@googlegroups.com> (permalink)
References <jvp75j$opr$1@news.albasani.net>

Show all headers | View raw


On Monday, August 6, 2012 12:50:13 PM UTC-7, 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

When you pass a list (mutable object) to a function, the pointer to the list is passed to the function and the corresponding argument points to the same memory location as the pointer passed in. So in this case, nlist points to the same memory location which u points to when xx is called,  i.e. nlist and u points to same memory location which contains [1,2,3,4].

nlist += [999]  is equivalent to nlist.extend([999]). This statement adds the argument list to the original list, i.e. the memory location pointed by nlist  and u now contains [1,2,3,4,999]. So, print(u) after calling xx will print [1,2,3,4,999].

 nlist += [999] is not the same as nlist = nlist + [999]. In the later case, nlist + [999] will create a new memory location containing the two lists combined and rebind nlist to the new location, i.e. nlist  points to a new memory location that has [1,2,3,4,999]. So if nlist = nlist +[999] is used, the original memory location containing [1,2,3,4] is untouched, and print(u) after calling xx will print [1,2,3,4]

Back to comp.lang.python | Previous | NextPrevious 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