Pregunta

I am writing a program in Python. I have a 2-D matrix implementation using lists that I have declared outside the scope of all the function. The idea is to store in the matrix values computed from subsequent function calls. My code is something like this:

database=[[0 for i in range(2)] for j in range(2)] #2-D matrix

def func(data,x,y):
   #manipulate the list data and then store it in database[x][y]
   data[1]+=1
   database[x][y]=data

   print("database[0][0]={}, database[1][1]={}".format(database[0][0], database[1][1]))
   del data[:]

def main():
   data=['one',1]
   func(data,0,0)

   data=['two',2]
   func(data,1,1)

if __name__=="__main__":main()

At the end, i am getting database[0][0] as something different. I am wondering why index [0][0] does not have ['one', 2]! Any help would be appreciated. Thanks!

¿Fue útil?

Solución

In func when you do del data[:] you delete the object that the local argument data is pointing to. So even though you've stored a reference to it in the database it's gone.

You can either:

  • remove the delete statement, local variables will be discarded anyways, there is no need for this
  • Use database[x][y]=list(data) instead to make a copy of data as a new object
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top