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 OverflowHow to initialize a two-dimensional array (list of lists, if not using NumPy) in Python? - Stack Overflow
Explain 2D Lists
2D array ( list ) in Python
https://www.reddit.com/r/learnpython/wiki/faq#wiki_why_is_my_list_of_lists_behaving_strangely.3F
More on reddit.comWhy are 2D arrays in Python so stupid?
Videos
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]]
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) /
Hi redditors!
I'm learning Python and I have to do a project with 2D lists. I'm fairly new to programming and I'm having a hard time understanding the format of a 2D list.
I'm trying to create rows and columns with '.' but I can only print out one row.....can someone help me by giving a simple example on how to do 2D lists, please? Oh, and reddit is my last resource. I have been looking for material I can understand but I'm having trouble :_(
Hello, I created a 2D array ( list) in 2 different ways. For some reason I am getting different answers when I run a recursive program using these 2 lists: Which is the correct Python way to do it, I am getting incorrect answers using the first method, although the dimensions of the 2 arrays are absolutely the same
First way:
m = [[None]*(len(denoms))]*(n+1)
Second way:
m = [None] * (n+1)
for row in range(n+1):
m[row] = [None] * len(denoms)https://www.reddit.com/r/learnpython/wiki/faq#wiki_why_is_my_list_of_lists_behaving_strangely.3F
First way will have reference to same list object (which is mutable) for all element in outer list.
So changing one will change other list too. If you are doing after this code, you will see the effect.