Arrays Merging Instead of Appending in Python

81 Views Asked by At

I'm attempting to append these two arrays as they're built but am getting unexpected results in Python:

This = []
That = []

This.append('A')
That.append(This)

This.append('B')
That.append(This)

print(That)

Expected results: [['A'],['A','B']]

Actual results: [['A','B'],['A','B']]

Whereas this works as expected:

That = []

This = ['A']
That.append(This)

This2 = ['A', 'B']
That.append(This2)

print(That)

Expected results: [['A'],['A','B']]

Actual results: [['A'],['A','B']]

4

There are 4 best solutions below

1
Jonatan Doffe On

You have to think of the "this" as just one object, if you want 2 different objects in you have to copy a copy of this like That.append(This.copy())

https://docs.python.org/3/library/copy.html

0
Alexcom On

The problem arises on line 7 of your code. When I am updating This array the second time with This.append('B'), it is automatically updated in That array.

Similar issue:

Python list updating elements when appending

Hope this helps.

0
Syeda Maira Saad On

The reason you're getting unexpected results is because both This and That are referring to the same list object. When you append This to That, you're appending a reference to the same list object. So when you modify This, it reflects in both places where it's referenced.

To achieve the expected results, you need to make a copy of This when appending it to That, so that modifications to This don't affect the elements already appended to That.

This = []
That = []

This.append('A')
That.append(This.copy())

This.append('B')
That.append(This.copy())

print(That)
0
Suramuthu R On

To understand this, add print statement after each line and see the output. Explanation given

This = []
That = []

This.append('A')
print(This)  #Output : ['A'] 
#Now This has become ['A]


# appending This to that. (i.e) appending ['A'] to [] should give [['A']]
That.append(This)
print(That) # Output : [['A']]


# This is ['A']. If 'B' is appended, this becomes ['A', 'B']. But this is already inside that. that becomes [['A', 'B']]
This.append('B')
print(This) # Output : ['A', 'B']
print(That)

#Now  that is [['A', 'B']]. this is ['A', 'B']. appending this to that, that becomes [['A', 'B'], ['A', 'B']]
That.append(This)
print(That)

So if at all you want to use the same object after appending but without change in appended list, create a copy of this

This = []
That = []
This.append('A')
That.append(This)
There = This.copy()
There.append('B')
That.append(There) 
print(That) #Output: [['A'], ['A', 'B']]