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
python - How to define a two-dimensional array? - Stack Overflow
Explain 2D Lists
How to define a two-dimensional list in Python like this? - Stack Overflow
How do I create a 2D list in Python?
How do I access a value in a Python 2D list?
When should I use NumPy instead of a 2D list?
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) /
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.
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 :_(
That is, indexes should be separated by
[], instead of being putting together in one[]separated by comma.
a[0,1] is equivalent to a[(0, 1)], which calls a.__getitem__((0, 1)).
a[0][1] is equivalent to a.__getitem__(0).__getitem__(1). As you can see, the brackets are really just a nice way of calling __getitem__.
Python lists only support integers and slice objects as the arguments to __getitem__, so you can't write a[0, 1]. You can, however, write your own class and have __getitem__ do whatever you want:
>>> class Something(object):
... def __getitem__(self, arg):
... return arg
...
>>> Something()[{1, 2, 3}, {4, 5, 6}, 'foo', ..., 12, 4:2]
({1, 2, 3}, {4, 5, 6}, 'foo', Ellipsis, 12, slice(4, 2, None))
Even though Python lists do not have more than one dimension the notation with two or more indices / slices is needed for arrays / matrices which come with numpy. Even though it (intentionally) doesn't belong to the core library it has become a de facto standard for n-dimensional arrays.
Here you can type
>>> import numpy as np
>>> ar = np.array([[1,2],[3,4]])
>>> ar[0,0]
1
>>> ar[:,0]
array([1, 3])
>>> random_array = np.random.random((100,100))
>>> random_array[50:60,30:35]
array([[ 0.8352567 , 0.14901839, 0.2409099 , 0.88278442, 0.84300552],
[ 0.88403713, 0.54964811, 0.83500869, 0.88258427, 0.90273584],
[ 0.00271817, 0.94116153, 0.6282039 , 0.3243262 , 0.71785796],
[ 0.0661821 , 0.99243509, 0.5888741 , 0.04161134, 0.89517395],
[ 0.87419943, 0.14761041, 0.06123542, 0.8139316 , 0.66220133],
[ 0.24710625, 0.02305463, 0.7301232 , 0.11279152, 0.57674316],
[ 0.9893136 , 0.9711931 , 0.12936097, 0.49021876, 0.24834283],
[ 0.48277394, 0.76470469, 0.29348414, 0.43578663, 0.69670601],
[ 0.43401812, 0.14714134, 0.52015761, 0.40088974, 0.25203087],
[ 0.9431969 , 0.04824567, 0.98400652, 0.1129802 , 0.25518842]])
Custom classes seem to be a very special use case - numpy arrays are really used a lot, almost no scientific Python library does not use numpy.