0

Exmaple 1

a = [1,[2,3],[4]]
b = a[1]
print(b)

Output:
[2, 3]    


b[1] = 88
print(a)
print(b)


Output:
[1, [2, 88], [4]]
[2, 88]

Example 2

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

Output:
1


b = 88
print(a)
print(b)

Output:
[1, [2, 3], [4]]
88

Example 3

a = [1,[2,3],[4]]
b = a[2]
print(b)

Output: 
[4]

b = 88
print(a)
print(b)

Output:
[1, [2, 3], [4]]
88

Example 4

a = [1,[2,3],[4]]
b = a[2]
print(b)

Output:
[4]


b[0] = 88
print(a)
print(b)

Output:
[1, [2, 3], [88]]
[88]

So when a is a list of list, and b is assigned a list value then a change of value in b changes the original list. However, when b is assigned just a regular value then a change in value in b does not change the original list. Then in the last two examples we see that even if b is a list but if we assign it a value then it doesnt change the original list. Why is this the case? What types of structures have this property where the assignment in some secondary variable changes the original variable?

Amatya
  • 1,203
  • 6
  • 32
  • 52
  • 1
    [`refer this`](https://stackoverflow.com/a/47258728/4985099) answer exact problem is discussed here. – sushanth Aug 22 '20 at 05:26
  • 1
    A list is "a regular value". The difference is, in one case, you mutate the list object `b[1] = 88`. In the other case, you don't mutate the `int` object (you *can't*, int objects are immutable), you simply re-assign the variable, `b = [2, 88]`. You'll see **the exact same behavior** if you re-assign with a list, so, `b = a[1]` then `b = 88`. Then `print(a)` and you'll see, the list at `a[1]` hasn't been modified. You should read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Aug 22 '20 at 05:28
  • 1
    "What types of structures have this property where the assignment in some secondary variable changes the original variable" **none** do. That isn't what's happening. Regular assignment is just `a = whatever`, instead, you are using *index* assignment, `a[index] = whatever`, which is essentially just a method call, `a.__setitem__(index, whatever)`, and in the case of `list` objects, this is a mutator method. simple assignment **never mutates** – juanpa.arrivillaga Aug 22 '20 at 05:30

0 Answers0