A difficulty with lists

MRAB python at mrabarnett.plus.com
Mon Aug 6 16:19:01 EDT 2012


On 06/08/2012 20:50, 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?
>
This:

     nlist+=[999]

appends to the list, making it [1, 2, 3, 4, 999].

This:

     nlist=nlist[:-1]

gets a slice of the list and then binds it to the local name 'nlist'.




More information about the Python-list mailing list