zud
zud

Reputation: 169

Python, appending a list to another list

I need to append a list to a 2D list so that I can edit the added list. I have something like this:

n = 3
a = [
    ['a', 2, 3],
    ['b', 5, 6],
    ['c', 8, 9]
]
b = [None for _ in range(n)]    # [None] * n
print b
a.append(b)
a[3][0] = 'e'
print a
a.append(b)
a[4][0] = 'f'
print a

The result I am getting is:

[None, None, None]
[['a', 2, 3], ['b', 5, 6], ['c', 8, 9], ['e', None, None]]
[['a', 2, 3], ['b', 5, 6], ['c', 8, 9], ['f', None, None], ['f', None, None]]  

The e in 4th row changes to f, which I don't want. With [None] * 3 I get same result. How do I prevent this from happening? I checked how to create a fix size list in python and python empty list trick but it doesn't work.

Upvotes: 1

Views: 910

Answers (2)

Abdel
Abdel

Reputation: 97

Because your shallow copying the list instead of deep copying it (see: What is the difference between shallow copy, deepcopy and normal assignment operation? ). Instead, you can use inbuilt module copy do the following:

import copy
# replace a.append(b) with the following
a.append(copy.deepcopy(b))

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

b is "pointing" to the same python object

You should do this instead to create new copies of b:

a.append(list(b))

Upvotes: 6

Related Questions