-1
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ Mutable vs immutable variables. Ints are immutable. $\endgroup$ – Emre Aug 29 '17 at 15:22
2
$\begingroup$

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.

$\endgroup$
  • 2
    $\begingroup$ Additionally, slicing copies sequences b = a[:] (from python documentation) $\endgroup$ – Sophie Searcy - Metis Aug 29 '17 at 15:24
  • $\begingroup$ @SophieSearcy yes, slicing is another way around. I'll edit my answer with slicing too. $\endgroup$ – i.n.n.m Aug 29 '17 at 15:25
  • $\begingroup$ 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. $\endgroup$ – user13985 Aug 29 '17 at 15:49
  • 1
    $\begingroup$ 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/… $\endgroup$ – i.n.n.m Aug 29 '17 at 15:55
  • 1
    $\begingroup$ 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 $\endgroup$ – i.n.n.m Aug 29 '17 at 19:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.