1

I'm initializing a list and then updating values in it, however the variable I am using for initializing the rows is also getting updated retrospectively - so to speak.

I expected this code to output [['first', ''], ['', 'last']]. How can I change my code so it outputs that?

array_row = ['', '']
array = []
# array = [['', '']]
array.append(array_row)
# array = [['first','']]
# array_row = ['first', '']  <---- !!! Why does array_row also get updated???
array[0][0] = 'first'
# array = [['first',''], ['first','']]
# array_row = ['first', '']
array.append(array_row)
# array = [['first','last'], ['first','last']]
# array_row = ['first', 'last']   <---- !!! Why does array_row also get updated???
array[1][1] = 'last'
# [['first', 'last'], ['first', 'last']]
print(array)
Mohammad
  • 7,344
  • 15
  • 48
  • 76
  • It doesn't retrospectively do anything. It's the same list, you're adding two references to it into the outer list. – jonrsharpe Jun 18 '20 at 07:23
  • Python doesn't make copies the way you're expecting. See https://nedbatchelder.com/text/names.html – user2357112 Jun 18 '20 at 07:23
  • Thanks for this but how do I then append my list with empty values? In the way that I am trying to achieve in my code? I am not trying to make a copy. – Mohammad Jun 18 '20 at 07:26
  • Well you should be! Because if you don't make a copy and just keep reusing the same list, you've seen what happens. – jonrsharpe Jun 18 '20 at 07:53

0 Answers0