john morrison
john morrison

Reputation: 187

Why is python copying lists here?

I have a function that is supposed to represent a cube out of a "3D" array, but with one layer having a square in the middle. I.E.

def cube(n):
    list1 = []
    list2 = []
    list3 = []


    for a in range(n+2):
        list3.append(str('c'))
    for b in range(n+2):
        list2.append(list(list3))
    for c in range(n+2):
        list1.append(list(list2))


    for d in range(1,n+1):
        for e in range(1,n+1):
            list1[0][d][e]='h'
    return list1

pprint.pprint(cube(2))

>>>

[[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],

[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],

[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],

[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']]]

but I would like this:

>>>

[[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],

[['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']],

[['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']],

[['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']]]

An h in the first layer only. Why is python doing this?

Upvotes: 1

Views: 53

Answers (1)

Tim Peters
Tim Peters

Reputation: 70602

Here's a minimal change to get what you want. First, add

from copy import deepcopy

Then replace:

list1.append(list(list2))

with:

list1.append(deepcopy(list2))

Upvotes: 2

Related Questions