A difficulty with lists

Madison May worldpeaceagentforchange at gmail.com
Thu Aug 16 01:56:26 CEST 2012


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

I've modified your code slightly so you can see what's happening with u in the middle of function xx.  Take a look:

u=[1,2,3,4]

def xx(nlist):
    print("xx(u)\n")
    print("At first, u and nlist refer to the same list")
    print("nlist: %s   u: %s\n" % (nlist, u))
 
    nlist+=[999]

    print("nlist+=[999]\n")
    print("The list has been modified in place.  u and nlist are still equal")
    print("nlist: %s   u: %s\n" %(nlist, u))
 
    nlist=nlist[:-1]
 
    print("nlist=nlist[:1]\n")
    print("Now nlist refers to a new list object in memory that was created by")
    print("taking a slice of u.  u and nlist are no longer equal.")
    print("nlist: %s   u: %s" %(nlist, u))
    
xx(u)

Here's the output:


xx(u)

At first, u and nlist refer to the same list
nlist: [1, 2, 3, 4]   u: [1, 2, 3, 4]

nlist+=[999]

The list has been modified in place.  u and nlist are still equal
nlist: [1, 2, 3, 4, 999]   u: [1, 2, 3, 4, 999]

nlist=nlist[:1]

Now nlist refers to a new list object in memory that was created by
taking a slice of u.  u and nlist are no longer equal.
nlist: [1, 2, 3, 4]   u: [1, 2, 3, 4, 999]


Thank you, Rob Day, for explaining a some of what's happening behind the scenes.



More information about the Python-list mailing list