A strange list concatenation result

ast nomail at com.invalid
Sun Aug 14 07:06:25 EDT 2016


"Mok-Kong Shen" <mok-kong.shen at t-online.de> a écrit dans le message de 
news:noo1v6$r39$1 at news.albasani.net...
> Am 13.08.2016 um 03:08 schrieb Steven D'Aprano:
>> On Sat, 13 Aug 2016 06:44 am, Mok-Kong Shen wrote:
>>
>>>>>>> list2 = [1,2,3]
>>>>>>> list1 += [4,5,6]
>>>>>>> print(list1, list2)
>>>> [1, 2, 3, 4, 5, 6] [1, 2, 3]
>>>>
>>>>
>>>> Does that help?
>>>
>>> I don't yet understand why in my 2nd example list2 came out as
>>> [1, 2, 3] outside.
>>
>> Because you assign list2 = [1, 2, 3]. What did you expect it to be?
>
> But in my function test() there is a code line "list2=list2+[4,5,6]".
> Could you kindly explain why this didn't work?
>
> M. K. Shen
>

Hello

list1 += [4, 5, 6 ] is slightly different than list1 = list1 + [4, 5, 6]

see:

>>> list1 = [1, 2, 3]
>>> id(list1)
45889616
list1 += [4, 5, 6 ]
>>> id(list1)
45889616   # < -same address
>>> list1
[1, 2, 3, 4, 5, 6]

so list1 += [4, 5, 6 ]  updates the existing list

>>> list1 = [1, 2, 3]
>>> id(list1)
45888656
>>> list1 = list1 + [4, 5, 6]
>>> id(list1)
45862424 # <- a new address
>>> list1
[1, 2, 3, 4, 5, 6]

so list1 = list1 + [4, 5, 6] create a new list 




More information about the Python-list mailing list