1

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.

1
  • Your formulation could be improved: b is not an empty list, since its length is 3. Commented May 13, 2016 at 12:34

2 Answers 2

6

b is "pointing" to the same python object

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

a.append(list(b))
Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.