0

I have the list:

DATA = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
        [6, 0, 0, 1, 9, 5, 0, 0, 0],
        [0, 9, 8, 0, 0, 0, 0, 6, 0],
        [8, 0, 0, 0, 6, 0, 0, 0, 3],
        [4, 0, 0, 8, 0, 3, 0, 0, 1],
        [7, 0, 0, 0, 2, 0, 0, 0, 6],
        [0, 6, 0, 0, 0, 0, 2, 8, 0],
        [0, 0, 0, 4, 1, 9, 0, 0, 5],
        [0, 0, 0, 0, 8, 0, 0, 7, 9]]

In a test_function i change 1 number of this list:

def test_check_value(self):
        DATA[1][3] = 7...

(I do this in multiple functions with other numbers)

At the end my whole list have changed. What can I do so that the functions just test it (with the changed value) and dont change the value of my main list?

Sven
  • 153
  • 2
  • 17

3 Answers3

2

Use copy.deepcopy at the beginning of each test

>>> import copy
>>> l1 = [[1, 2], [3, 4]]
>>> l2 = copy.deepcopy(l1)
>>> l2[0][0] = 9
>>> l2
[[9, 2], [3, 4]]
>>> l1
[[1, 2], [3, 4]]

Note that it works well because you keep integers inside the nested list. If it was some modifiable data structure, deepcopy would create new instances.

Bartosz Marcinkowski
  • 6,651
  • 4
  • 39
  • 69
1

You could locally copy the list, to do this you can use the copy.deepcopy function.

import copy

def test_check_value(self):
    local_list = copy.deepcopy(DATA)
    local_list[1] = 0

I think interesting to note that using the built-in list() function to copy does not work for nested lists, so in this case copy.deepcopy has to be used.
Thanks @Bartosz Marcinkowski for pointing that out.

For further information on lists copies, see http://stackoverflow.com./a/2612815/2549230

d6bels
  • 1,432
  • 2
  • 18
  • 30
0

It seems that you have defined your list as global.thus for get ride of this situation you need to pass a copy of your list to your function , you can use [a[:] for a in DATA] to copy your nested list or use copy.deepcopy():

my_list=[a[:] for a in DATA]
def test_check_value(self,my_list): 
Mazdak
  • 105,000
  • 18
  • 159
  • 188