Home > Software engineering >  Why does a = [10, 20, 30, 40] not [10, 20] in this case?
Why does a = [10, 20, 30, 40] not [10, 20] in this case?

Time:02-04

a = [10, 20]
b = a  
b  = [30, 40]  
print(a)
print(b)

I understand that b = = [10, 20, 30, 40], but I don't understand why a = [10, 20, 30, 40]?

CodePudding user response:

In Python, a variable is actually a reference to an object.

>>> a = [10, 20]
>>> b = a
>>> id(a)
140351945078976
>>> id(b)
140351945078976

In this case, both a and b were referenced to same array [10, 20]. When you append b, a will have same object and see it.

If you want to have a different object, you should do b = a[:] or b = a.copy()

CodePudding user response:

b and a both refer to the same list object.

CodePudding user response:

Because of b = a, both a and b point out same memory.

You can check detailed information and examples here: https://www.geeksforgeeks.org/is-python-call-by-reference-or-call-by-value/

In python, each variable to which we assign a value/container is treated as an object. When we are assigning a value to a variable, we are actually binding a name to an object.

CodePudding user response:

What you are experiencing is the concept of references. All objects in Python have a reference and when you assign one to two names a and b, this results in both a and b pointing to the same object.

CodePudding user response:

I ran into this problem when working with Python for a bit. When you say b = a in the code above, you are actually creating a pointer to a in memory. Any changes done on b will affect a because b points to a in memory.

If you aren't familiar with pointers I would check them out for the language you are using.

CodePudding user response:

In Python, if two variables are assigned with the same value, then they point to the same object in the memory, like in this case when b=a then a and b are pointing to the same object in the memory when you make change using b to the object like b = [30, 40] then the object pointing by a and b both has changed giving you the final output [10,20,30,40]

if you use the code below then your output will be [10,20] for a and [10,20,30,40] for b as the object pointing was changed after printing a

`a = [10, 20], b = a, print(a),

b = b [30, 40] ,
print(b)`

  •  Tags:  
  • Related