A difficulty with lists

Cheng chbeh88 at googlemail.com
Mon Aug 20 16:43:54 EDT 2012


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]



More information about the Python-list mailing list