Home > Mobile >  why does clearing a list also clears all variables set to equal that list?
why does clearing a list also clears all variables set to equal that list?

Time:11-28

Using Python 3.8.10

I can from a C background and was doing a project in python3 where I noticed this:

a = [1,2,3,4]
b = a
a = [8]
print(b)  // this gives [1,2,3,4]

but when I do a.clear

a = [1,2,3,4]
b = a
a.clear()
print(b)  // this gives []

why is that?

CodePudding user response:

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();
  • Related