I am using Python 3.4.
I noticed this curious behaviour:
In [1]: a=[1,2,3,4,5,6,7,8,9]
In [2]: b=[10,11,12,13,14,15,16,17,18,19]
In [3]: type(a)
Out[3]: list
In [4]: a
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [5]: b
Out[5]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [6]: c=a
In [7]: c
Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [8]: c.extend(b)
In [9]: c
Out[9]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [10]: a
Out[10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Why is a modified by the extend method applied on c?
Do you observe the same behaviour?
Is it normal? And in this case, how can I extend c leaving a intact?
Because you set c as a some lines before you assign c on line In [6].
Edit: Since my answer is not that deep have a look at that.
You want to make c as a new list by copying a. But there are two ways to copy: shallow and deep copy.
You want to have two seperate lists so you need deepcopy.
You cannot use list() since it will shallow copy your list and so both your lists will still be 'connected'. When you change one value it will be changed in the other list as well.
When you use
c = copy.deepcopy(a)
You will get two separate lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With