Using nested comprehension lists :
x = [[None for _ in range(5)] for _ in range(6)]
Answer from Vincent Savard on Stack Overflowlist - Creating a 2d matrix in python - Stack Overflow
Python create empty 2-dimensional array - Stack Overflow
python - How to define an empty 2 dimensional list instead of data = [["",""],["",""],["",""],["",""]] - Stack Overflow
Explain 2D Lists
Using nested comprehension lists :
x = [[None for _ in range(5)] for _ in range(6)]
What's going on here is that the line
x = [[None]*5]*6
expands out to
x = [[None, None, None, None, None, None]]*6
At this point you have a list with 6 different references to the singleton None. You also have a list with a reference to the inner list as it's first and only entry. When you multiply it by 6, you are getting 5 more references to the inner list as you understand. But the point is that theres no problem with the inner list, just the outer one so there's no need to expand the construction of the inner lists out into a comprehension.
x = [[None]*5 for _ in range(6)]
This avoids duplicating references to any lists and is about as concise as it can readably get I believe.
You get the IndexError because you can't assign to an index in the list beyond the current length of the list. Since grid2 is initialized to an empty list, any attempt to index it will raise this error.
One correct way to write your nested list comprehension using for loops would be to construct the inner list first for each row, then append this to grid2:
grid2 = []
for i in range(rows):
inner = []
for j in range(cols):
inner.append(0)
grid2.append(inner)
you should initialize grid2=np.empty([rows, cols]) instead please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html#numpy.empty for more details
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 :_(