0

I have the function below:

def set_x(self,index1, index2, val):
    print('Setting X with index1 : ' + str(index1) + ' , index2 : ' + str(index2) + ' with value : ' + str(val))
    print(self.x)
    self.x[index1][index2] = val
    print(self.x)
    print('hehe')

Say for example I called it, with parameters, 0, 1 and 785. The actual ouput is below:

Setting X with index1 : 0 , index2 : 1 with value : 785
[[305, 665], [305, 665]]
[[305, 785], [305, 785]]

Im expecting it to be:

Setting X with index1 : 0 , index2 : 1 with value : 785
[[305, 665], [305, 665]]
[[305,785],[305,665]]

It's like my assignment is setting all the second element of all the array within the array. How will I fix it?

alyssaeliyah
  • 2,214
  • 6
  • 33
  • 80
  • 1
    It should work! Your function is correct, the error is coming from other parts of code. – vrintle Nov 18 '18 at 06:41
  • 1
    @rv7 --> maybe because self.x is access by multiple applications. – alyssaeliyah Nov 18 '18 at 06:45
  • Yes, it could be the possible reason. – vrintle Nov 18 '18 at 06:46
  • You should look at this https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Canh Nov 18 '18 at 06:48
  • Why are you tagging your question with [tag:array] ? you are handling `list`s - arrays are in numby or the array module. Why are you tagging [tag:python-2.7] **and** [tag:python-3.x] - are you :really_ workng on a cross-3.x-2.7 solution ? Only tag what you really use and has _importance_ for your code. Did you read any of the tag descriptions? – Patrick Artner Nov 18 '18 at 08:21

1 Answers1

3

it can be because the two list in the self.x are referenced to the same list. It depends on how you created x in the first place. Look at this example

a=[305,665]
x = []
x.append(a)
x.append(a)
x[0][1]=3
print(x)
#[[305, 3], [305, 3]]

when you are setting the value ox x[0][1], what you are really doing is changing the value of a[1] and hence both the list are changing. You should use copy of the list instead.

from copy import deepcopy
a = [305, 665]
x = []
x.append(deepcopy(a))
x.append(deepcopy(a))
x[0][1] = 3
print(x)
#[[305, 3], [305, 665]]
vrintle
  • 5,501
  • 2
  • 16
  • 46
Biswadip Mandal
  • 534
  • 1
  • 4
  • 15
  • Thank you so much. It took me days, trying to figure it out. I am developing a game and because of this small thing, Im completely stressed finishing my project. Thank you and Abba Yahweh bless you. – alyssaeliyah Nov 19 '18 at 02:51