Why the result is 3 not 2? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the result is 3 not 2?

a=[1,2] b=a a.append(3) print(len(b))

16th Feb 2019, 4:48 PM
zlyx525
5 Answers
+ 6
Variable names are like labels in python. "b=a" adds another label to the list a, so you can now use both "a" and "b" to address the same list. Whatever happens to b, happens to a and vice versa. If you want to copy the list instead of just adding another label, use b = a[:] or b = list(a).
16th Feb 2019, 5:07 PM
Anna
Anna - avatar
+ 5
In this case b and a are two variables that reference the same list (point to the same memory location). Therefore if the value of a changes, same thing happens to b. To copy the list a to a separate and independent variable, you would have to slice it for example: b = a[:]
16th Feb 2019, 5:10 PM
Tibor Santa
Tibor Santa - avatar
+ 5
A list is what is known as a ‘mutable’ object. This essentially means that, when you have a statement b=a, changing a also changes b. So in your code, b=a means that b is set as the same as a, and when b is changed, so is a. So when a gets 3 appended to it, it affects b too. Since the length of a (and hence b too) is now 3, that is what is returned.
16th Feb 2019, 5:11 PM
Russ
Russ - avatar
+ 4
b is a reference to a and not a copy of it.
17th Feb 2019, 10:06 PM
Sonic
Sonic - avatar
0
if you want the result is 2 you should applying copy method.
17th Feb 2019, 8:30 AM
amirreza shamsdanesh
amirreza shamsdanesh - avatar