-1

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']]

5
  • 1
    You appended This twice, that's what you get in That. Commented Mar 4 at 6:50
  • 1
    Consider list names in python as "pointers" to the same list. Try a print(This). This will reveal This=['A','B']. Commented Mar 4 at 6:56
  • Does this answer your question? How do I clone a list so that it doesn't change unexpectedly after assignment? Commented Mar 4 at 7:17
  • Unhelpful comment, Diego Torres Milano, I adjusted the post to show an example of why this would be unexpected behavior. destructioneer - thank you for this, considering it like pointers is helpful in making sense out of what it's doing. Commented Mar 5 at 0:02
  • That link was helpful, Abdul Aziz Barkat, thank you. Commented Mar 5 at 0:14

3 Answers 3

2

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

1
  • Thank you for the response, Jonatan! I selected Mukul Tripathi for the accepted answer due to the additional information about mutable objects. Commented Mar 5 at 0:03
0

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

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']]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.