A strange list concatenation result
Gary Herron
gherron at digipen.edu
Thu Aug 11 17:49:40 EDT 2016
On 08/11/2016 03:06 PM, Mok-Kong Shen wrote:
>
> def test(list1,list2):
> list1+=[4,5,6]
> list2=list2+[4,5,6]
> print("inside ",list1,list2)
> return
>
> # With
>
> list1=list2=[1,2,3]
> test(list1,list2)
> print("outside",list1,list2)
>
> # I got the following:
> # inside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 4, 5, 6]
> # outside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
>
> # With
>
> list1=[1,2,3]
> list2=[1,2,3]
> test(list1,list2)
> print("outside",list1,list2)
>
> # I got the following:
> # inside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
> # outside [1, 2, 3, 4, 5, 6] [1, 2, 3]
I think the following shows the same issue in a much simpler fashion:
In this (and your first) example, there is only one list, although it
has two names to reference it.
>>> list1 = list2 = [1,2,3]
>>> list1 += [4,5,6]
>>> print(list1, list2)
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
In this next example, there are two separate lists:
>>> list1 = [1,2,3]
>>> list2 = [1,2,3]
>>> list1 += [4,5,6]
>>> print(list1, list2)
[1, 2, 3, 4, 5, 6] [1, 2, 3]
Does that help?
Gary Herron
--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418
More information about the Python-list
mailing list