+ 5
Why the output is [1,2,3,4,5,6] not [1,2,3]
a=[1,2,3] b=a b+=[4,5,6] print(a)
7 Answers
+ 10
Huh. First I didn't see the point of your question but now I understand. In the end you are printing a, but you made the assignment with b.
First point, if you try the code below, it will prove that a and b are two variables pointing to the same object. The id() function shows the memory reference of a value.
a = [1, 2, 3]
b = a
print(id(a) == id(b)) # True
So this means, if you modify b, then a is also automatically modified.
The other part is really tricky and I found the solution in stackoverflow.
https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists
"The general answer is that += tries to call the __iadd__ special method, and if that isn't available it tries to use __add__ instead. So the issue is with the difference between these special methods."
So in your sample code, the assignment b+=[4,5,6] actually does an in-place mutation on b, which is then also reflected in a.
+ 4
b=a[:]
0
This is logical! Take a look at your code once more. You created 2 list variables 'a' and 'b' right? a is assigned with [1,2,3] ; variable b is assigned with variable a's, which has automatically set b to a with its value, now you now incremented b with [4,5,6], this will concatenate what value contain in variable a with the new value of b. You have set the values of a and b to the same thing. Print b and see also.
0
b=a.copy()
0
Python List Copy Example - How To Clone or Copy List in Python?
https://www.stechies.com/clone-copy-list-python
0
When we wrote "b=a" then b is become 'a' so,after when you calling' b' but it already converted into 'a' so,then is b+=[4,5,6] is considered as a+=[4,5,6]
that's why the output [1,2,3,4,5,6]
0
Sister can u help me