+ 1
Why the result is 3 not 2?
a=[1,2] b=a a.append(3) print(len(b))
5 Antworten
+ 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).
+ 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[:]
+ 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.
+ 4
b is a reference to a and not a copy of it.
0
if you want the result is 2 you should applying copy method.