A difficulty with lists

Madison May worldpeaceagentforchange at gmail.com
Wed Aug 15 23:12:01 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

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).



More information about the Python-list mailing list