0

I want to make list b equal to list a, and then change b without influencing a.

a = "1234"
b = ""
a = list(a)
b = a

When I print(a) after changing b, a changes as well. Although in the code below, I don't get this problem, meaning whatever change I make to variable b, a will stay independent.

a = "1234"
b = ""
a = list(a)
b = list(a)

I am looking for an explanation on what happened behind the scenes and why the second code example worked.

R Harrington
  • 253
  • 2
  • 10
  • 1
    Names (variables) are references to objects in Python. If you do `b = a` you will make `b` reference to the same object `a` references to. If you want to make a shallow copy of a list, just use `b = a[:]` – Klaus D. Jun 22 '20 at 10:57
  • To complete @KlausD. 's comment, you can also copy the list with `b = a.copy()` (works the same with dictionaries btw) – Arount Jun 22 '20 at 10:58
  • https://stackoverflow.com/questions/19951816/python-changes-to-my-copy-variable-affect-the-original-variable Because of reference type – Gaurav P Jun 22 '20 at 11:00
  • you can read more about it with the buzzwords **view vs. copy python**. Also keep in mind that if you have e.g. a list of lists `[[1, 2], [3, 4]]` you need to do a deep copy like a.copy(deep=True) – Berger Jun 22 '20 at 11:42
  • 1
    @Berger Thank you for your response and reference for further reading :) I have tried to .copy() a list of lists and it seems to work fine (checked for id() and they are different too). Also, .copy(deep=True) produced the following error: "TypeError: copy() takes no keyword arguments" so I am a bit confused as to what was your point. – Davisko Jun 22 '20 at 12:21
  • @Davisko sorry, `.copy(deep=True)` was for DataFrames, I just saw for them it's on default set to True. Now to lists again: What I mean is the following: `a = [[1,2], [3,4]]` now do `b = a.copy()` if you check `id(a) == id(b)` will be false, but `id(a[0]) == id(b[0])` will be true, so you need to do a recursive copy. I just saw for lists you need to `import copy` and do `b = copy.deepcopy(a)` See [here](https://stackoverflow.com/questions/17873384/how-to-deep-copy-a-list) – Berger Jun 22 '20 at 13:22

1 Answers1

0

When you assign b=a, Python assigns by reference, so the variable b is just pointing to the same object as a. You can confirm this with the id() method that prints out the ID of the object:

>>> a="1234"
>>> id(a)
2858676454064
>>> b=a
>>> id(b)
2858676454064

When you do b = list(a), the list() method returns a new list.

>>> a = list(a)
>>> id(a)
2858676458880
>>> b = list(a)
>>> id(b)
2858676458944

After a = list(a), the a object is no longer the same as the a previously (2858676454064).

kamion
  • 461
  • 2
  • 9