# Why changing one element of a vector will change all variables? [closed]

Today I encountered this strange behavior in Python doing data manipulation. Why changing a will affect b below:

>>> a = ['Hello', 1, 2]
>>> b = a
>>> a[0] = 5
>>> b
[5, 1, 2]


I only asked a to change, why is b changing? But the following is fine,

>>> a = 3
>>> b = 4
>>> a
3
>>> b
4


My guess is that I am doing passing by reference(?). But in both cases are passing by reference, what is going on here?

• Mutable vs immutable variables. Ints are immutable. – Emre Aug 29 '17 at 15:22

In your first case, list what you're doing is copying a list, which is referencing a list to another list (ex: list b is referenced by list a).

In order to avoid that, you have to consider deepcopy in python in order to safely make edits to the copied list without those changes being reflected in the original.

For example,

 import copy
a = ['Hello', 1, 2]
b = copy.deepcopy(a)

a[0] = 5
print(b)  # This will give the original list
>> ['Hello', 1, 2]


This is the documentation that will be helpful.

Another way to get around as @Sophie mentioned in the comment is slicing,

b= a[:]

a[0] = 5

print(a)
>> [5, 1, 2]

print(b)
>> ['Hello', 1, 2]


In your second case, it is just a reference to a variable as you mentioned in the question.

• Additionally, slicing copies sequences b = a[:] (from python documentation) – Sophie Searcy - Metis Aug 29 '17 at 15:24
• @SophieSearcy yes, slicing is another way around. I'll edit my answer with slicing too. – i.n.n.m Aug 29 '17 at 15:25
• Thanks, how do I know if I am making a shallow copy or deep copy when using equal sign? There are list, dictionary, etc. The documentation is very technical to read. – user13985 Aug 29 '17 at 15:49
• As noted in the documentation deepcopy applies to list and dictionaries. If you are still want to know why? check this post stackoverflow.com/questions/2465921/… – i.n.n.m Aug 29 '17 at 15:55
• yes, you're right, sometimes we need something that preserve the old list or dictionary to perform data manipulation. I think this post's first answers especially by @cryo has what I have to say showing examples with timing copy.copy stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – i.n.n.m Aug 29 '17 at 19:37