This has to do with the way python copies lists.
When you do b.append(a)
you are actually appending the reference of a
, so when you change any value of a
it will also change b
:
Simplified depiction of what's happening:
# a = [] -> id_123
# b = [] -> id_321
a.insert(0,10)
# a = [10] --> id_123
b.append(a)
# b = [id123] = [[10]] --> id_321
a.insert(0,11)
# a = [10,11] --> id_123
b.append(a)
# b = [id123,id123] = [[10,11],[10,11]] --> id_321
In the end:
A => [12, 11, 10] --> id_123
B => [[12, 11, 10], [12, 11, 10], [12, 11, 10]] --> id_321
In the comments you have explained that you tried:
print(a is b)
# prints False
However, trying: a is b[0]
will give the expected result(True
):
for e in b:
print(a is e)
#prints True 3 times
Finally, if you were aiming to instead obtain:
A => [10]
B=> [[10]]
A => [11, 10]
B=> [[10], [11, 10]]
A => [12, 11, 10]
B=> [[10], [11, 10], [12, 11, 10]]
Then, you can simply change the appending to b
to:
b.append(a[:])
Here is a reference form another question here on SO:
From List changes unexpectedly after assignment. How do I clone or copy it to prevent this?:
With new_list = my_list, you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.
Full code:
a=[]
b=[]
n =10
for i in range(3):
a .insert(0,n+i)
print('A =>',a)
b.append(a[:])
print('B=>', b)