-3

Variable stores reference:

a = [3, 4]
list1 = [1, 2, a]
list1[2][0]=5
print(list1)
print(a)

output:

[1, 2, [5, 4]]

[5, 4]

Variable stores value:

a = 3
list1 = [1, 2, a]
list1[2]=5
print(list1)
print(a)

output:

[1, 2, 5]

3

Is there a rule I can remember? Cause sometimes I have to manipulate the variable indirectly and I don't know if it'll change the original or not.

NoName
  • 9,824
  • 5
  • 32
  • 52
  • 1
    https://stackoverflow.com/questions/184643/what-is-the-best-way-to-copy-a-list/184660#184660, It is good to make a copy :-) when you do object assignment – BENY Nov 06 '19 at 22:57
  • 5
    I'm not sure what you think this is showing. Variables are always references. – Daniel Roseman Nov 06 '19 at 22:58
  • 1
    [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) – wwii Nov 07 '19 at 00:04

1 Answers1

1

Variable always stores a reference.

The key to your confusion might be if the object that is referenced is mutable or not. In your first example a stores a reference to a list object which is mutable. In the second example a stores a reference to an immutable object of type int.

So this operation:

list1[2][0] = 5

modifies a reference stored in the list that a references to. So changes done to it are visible when you access the list via reference stored in a.

But this operation:

list1[2] = 5

Modifies a list element (which was initialized from the a) and now this element stores a reference to a new object. But a reference stored in a was not changed hence the result you get.

  • Okay, but why does `list1[2]=5` not change `a`, but `a = 5` does? Considering `list1[2]` contains `a`. Although `a` is immutable, I am assigning them to a new value, not modifying an existing one which should work either way. Unless, you're saying immutable types are passed as values and not references? – NoName Nov 06 '19 at 23:25
  • `list1[2]` does not contain `a`. It contains the reference to an `int` object with value `3`. `a` also contains the reference to the same object (of type `int` and value `3`) but these two reference are stored in different locations though they reference the same object. `list1[2]=5` modifies the value of the reference stored in `list1[2]`, this does not affect neither object of type `int` with value `3` nor the reference to it stored in `a`. Then immutable is the object of type `int` with value `3` but not the `a` (which is a variable that stores the reference to that object). – Roman-Stop RU aggression in UA Nov 06 '19 at 23:33
  • Hmmm, I see. So to achieve the same effect as the 2nd example in the 1st example. I would have to write `list1[2] = [5, 4]`. In this case, I would not be modifying the existing object pointed by both references, but pointing the reference in the list to a completely new object. And the output would be: `[1, 2, [5, 4]]` `[3, 4]`? – NoName Nov 06 '19 at 23:45