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) /
Explain 2D Lists
python - How to create a 2d list from a input data? - Stack Overflow
python - How to define a two-dimensional array? - Stack Overflow
2D list help in Python
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 :_(
You haven't declared ar yet. In Python, you don't have to perform separate declaration and initialization; nevertheless, you can't perform operations on names willy-nilly.
Start off with something like this:
ar = [[0 for j in range(m)] for i in range(n)]
You should know that ar is not defined when you are trying to perform an assignment like ar[i][j] = int(input()), there are many ways to fix that.
In C/C++
In C/C++, I presume you would do such work like this:
#include <cstdio>
int main()
{
int m, n;
scanf("%d %d", &m, &n);
int **ar = new int*[m];
for(int i = 0; i < m; i++)
ar[i] = new int[n];
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
scanf("%d", &ar[i][j]);
// Do what you want to do
for(int i = 0; i < m; i++)
delete ar[i];
delete ar;
return 0;
}
Before you get inputs by scanf in C/C++, you should allocate storage by calling new or malloc, then you can perform your scanf, or it will crash.
How to do like that in Python
It's very similar to what you had done in C/C++, according to your code, when you are trying to perform assignment to ar[i][j], Python has no idea what ar it is! So you have to let it know first.
A NOT-pythonic way
A NOT-Pythonic way is do something like you did in C/C++:
n = int(input())
m = int(input())
ar = []
for i in range(m):
ar.append([])
for j in range(n):
k = int(input())
ar[i].append(k)
for i in range(m):
for j in range(n):
print(ar[i][j])
You initialize the list by ar = [] like you did int **ar = new int*[m]; in C/C++. For each row in the 2-d list, initialize the row by using ar.append([]) like you did ar[i] = new int[n]; in C/C++. Then, get your data by using input and append it to ar[i].
A pythonic way
The way to perform such a job like above it's not very pythonic, instead, you can get it done by using a feature called List Comprehensions, then the code can be simplified into this:
n = int(input())
m = int(input())
ar = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
k = int(input())
ar[i][j] = k
for i in range(m):
for j in range(n):
print(ar[i][j])
Note that the core ar = [[0 for j in range(n)] for i in range(m)] is a list comprehension that it creates a list which has m lists and for each list of these m lists it has n 0s.
You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]
#You can now add items to the list:
Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.