-1

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?

  • FWIW, `.clear()` is pretty rarely used -- I've never used it personally. – Mateen Ulhaq Nov 28 '21 at 03:26
  • 2
    If you do this in C++, the exact same thing should happen. `a` and `b` refer to the same list. – Mateen Ulhaq Nov 28 '21 at 03:27
  • 1
    This is probably one of the better answers that explains this phenomenon [here](https://stackoverflow.com/questions/56667280/if-two-variables-point-to-the-same-object-why-doesnt-reassigning-one-variable) – Matthew Barlowe Nov 28 '21 at 03:45
  • @MateenUlhaq What data type do you think is the C++ equivalent of Python's `list`? – Kelly Bundy Nov 28 '21 at 04:07
  • @KellyBundy `std::vector& b = a;` https://replit.com/@SicariusNoctis/stdvector-reference#main.cpp – Mateen Ulhaq Nov 28 '21 at 05:13
  • @MateenUlhaq `std::vector&`? Ok. But you didn't do that for `a`. I tried changing `a` to `std::vector&` as well, didn't compile. – Kelly Bundy Nov 28 '21 at 05:40
  • @KellyBundy What do you think is the C++ equivalent of Python's `=`? I think the closest is `T& b = a;` for all non-primitive types. Similarly, python variables are similar to the type `T&`. If you want the types to match, try declaring a new vector `v` to store the data, then set `std::vector& a = v;`. – Mateen Ulhaq Nov 28 '21 at 06:24

1 Answers1

1

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();
rchome
  • 2,623
  • 8
  • 21