Q:

Python 3 comparing list variables

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.

A:

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).

