0

Given the following program, I want the variable bar to keep the same.

def foo(bar):
    bar2 = bar[:]
    chg = []
    for p in range(4):
        for q in range(3):
            chg.append([p,q])
    for [x,y] in chg:
        bar2[x][y] = "xx"
    return bar2

def printGrid(grid):
    for row in grid:
        print " ".join(row)    
    print

bar = [[str(i) + str(j) for i in range(5)] for j in range(6)]
printGrid(bar)
printGrid(foo(bar))
printGrid(bar)

However, this is the output:

00 10 20 30 40
01 11 21 31 41
02 12 22 32 42
03 13 23 33 43
04 14 24 34 44
05 15 25 35 45

xx xx xx 30 40
xx xx xx 31 41
xx xx xx 32 42
xx xx xx 33 43
04 14 24 34 44
05 15 25 35 45

xx xx xx 30 40
xx xx xx 31 41
xx xx xx 32 42
xx xx xx 33 43
04 14 24 34 44
05 15 25 35 45

I don't understand. The first 2 grids are as expected, but when did bar change? How can I prevent this from happening?

Lewistrick
  • 2,649
  • 6
  • 31
  • 42

1 Answers1

3

bar is a list of pointers. You are copying those pointers with bar2 = bar[:]. But, unless you change those pointers, they still point to the same lists, so bar[x][y] and bar2[x][y] refer to the same data. Try using

bar2 = copy.deepcopy(bar)

instead of

bar2 = bar[:]

You'll need to import copy

jrennie
  • 1,937
  • 12
  • 16