+ 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)

8th Nov 2022, 3:56 AM
SIMRAN
SIMRAN - avatar
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.
8th Nov 2022, 4:30 AM
Tibor Santa
Tibor Santa - avatar
+ 4
b=a[:]
8th Nov 2022, 6:45 AM
Oma Falk
Oma Falk - avatar
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.
9th Nov 2022, 10:25 AM
Jelili
Jelili - avatar
0
b=a.copy()
9th Nov 2022, 12:59 PM
SoloProg
SoloProg - avatar
0
Python List Copy Example - How To Clone or Copy List in Python? https://www.stechies.com/clone-copy-list-python
9th Nov 2022, 1:02 PM
SoloProg
SoloProg - avatar
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]
9th Nov 2022, 5:04 PM
♡GDY♡
♡GDY♡ - avatar
0
Sister can u help me
9th Nov 2022, 6:05 PM
Zubeyr Abukar
Zubeyr Abukar - avatar