1
items = [[1,2,3],[2,0,4],[3,4,1]]

def findzero(target):
    for i,lst in enumerate(target):
        for j,n in enumerate(lst):
            if n == 0:
                return [i, j]
    return (None, None)
        
def move_up(currState):
    result = currState[:]
    if findzero(result)[0] == 0:
        return result
    else:
        x = findzero(result)[0]
        y = findzero(result)[1]
        p = result[x - 1][y]
        result[x - 1][y] = 0
        result[x][y] = p
        return result

The result moved the 0 up but when I run the file, the 0 also moved up in the items variable. How can I move the zero up without change the original variable?

move_up(items)
Out[84]: [[0, 2, 3], [1, 2, 4], [3, 4, 1]]

items
Out[85]: [[0, 2, 3], [1, 2, 4], [3, 4, 1]]

I need items do not changed

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
rrryy39
  • 29
  • 3
  • See the `deepcopy` method from the [`copy` module](https://docs.python.org/3/library/copy.html#copy.deepcopy), which will give you a copy of the lists instead of references to the originals. – Kemp Apr 12 '21 at 09:09
  • ```import copy``` ```copy.copy``` and ```copy.deepcopy``` in https://docs.python.org/3/library/copy.html – Para Apr 12 '21 at 09:10
  • You can also have a look at https://stackoverflow.com/questions/17246693/what-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment-oper – Thierry Lathuille Apr 12 '21 at 09:11

1 Answers1

1

This

result = currState[:]

does create shallow copy, if you are sure that there always be exactly 2 levels (i.e. flat lists in single list) you might do

result = [i[:] for i in currState]

or equivalently

result = [i.copy() for i in currState]

if number of levels is not known in advance you might do

result = copy.deepcopy(currState)

(requires import copy)

Daweo
  • 31,313
  • 3
  • 12
  • 25