To initialize a two-dimensional list in Python, use
t = [ [0]*3 for i in range(3)]
But don't use [[v]*n]*n, it is a trap!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Answer from Jason CHAN on Stack OverflowTo initialize a two-dimensional list in Python, use
t = [ [0]*3 for i in range(3)]
But don't use [[v]*n]*n, it is a trap!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
A pattern that often came up in Python was
bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)
which helped motivate the introduction of list comprehensions, which convert that snippet to
bar = [SOME_EXPRESSION for item in some_iterable]
which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.
Your code follows this pattern twice
twod_list = [] \
for i in range (0, 10): \
new = [] \ can be replaced } this too
for j in range (0, 10): } with a list /
new.append(foo) / comprehension /
twod_list.append(new) /
What is the difference between these two methods of initializing a 2D matrix? (One is acting a little strange)
2 different ways to initialise a 2d list give different results
Need help with a two-dimensional array
how would you instantiate a two-dimensional array in the constructor?
In one of my programs, I need to to have a 2D matrix of boolean values initially set to all False.
One method to do it is:
matrix = [[False for i in range(n)] for j in range(m)]
which works fine.
But than I tried something like:
row = [False] * m matrix = [row] * n
Let's say n = m = 3
Initially, the matrix would be:
[[False, False, False], [False, False, False], [False, False, False]]
now, in the second method, if I set matrix[0][0] = True:
The expected result is:
[[True, False, False], [False, False, False], [False, False, False]]
but what actually happens is:
[[True, False, False], [True, False, False], [True, False, False]]
I figured this out and changed my method of initializing the matrix to the first one in my code. But just out of curiosity, can someone please explain what exactly is happening with method 2?
Thank you.....
P.S: Sorry if this is a stupid question :)
how would you instantiate a two-dimensional array in the constructor? would it be something like:
__init__(self, twoD_array = ([],[]))