In your second example, b
is a reference to a
. a.clear()
mutates the underlying list to be empty, so b
will also be empty. In the first example, a = [8]
will assign a new list to a
, but b
is still pointing to the previous reference to a
.
If I were to translate this to C++, the first example might look something like this. (I don't use C++ that often so this code might be weird)
std::vector<int> v1 = {1, 2, 3, 4};
std::vector<int>* a = &v1;
std::vector<int>* b = a;
std::vector<int> v2 = {8};
a = &v2;
The second example would look like
std::vector<int> v = {1, 2, 3, 4};
std::vector<int>* a = &v;
std::vector<int>* b = a;
(*a).clear();