Is there an way to create matrix[a][c][d] in python? It seems that you can write this way in Perl but not Python? Thanks!

A 2 dimensional matrix can easily be implemented as a list of lists

M = [
    [0, 1, 2],  # first row
    [3, 4, 5],  # second row
    [6, 7, 8], # third row
]

For heavy computations with matrices, there is a specialized module numpy .

Sorry I didn't make myself clear, I think it is like 4D matrix, so I can get an element like M[1][2][3][4], with list of list, it seems still 2D. Can I just nest list to reach 4D? Also how to iterate the matrix for initialization seems quite a task. Thanks!

It's not at all difficult, here is a code which creates a 4-dimensional tensor of size 2 x 4 x 3 x 2

# python 2 or 3
def zero_matrix(shape):
    if len(shape) == 1:
        return [0] * shape[0]
    else:
        return [zero_matrix(shape[1:]) for i in range(shape[0])]

if __name__ == "__main__":
    M = zero_matrix((2, 4, 3, 2))
    print(M)

The code works great! But I am not quite understand how zero_matrix function, could you explain a little bit? Thanks a lot!

It is a recursive function. The 'shape' argument is a non empty tuple like (2, 4, 3, 2).
Suppose by induction on the length of 'shape' that zero_matrix returns a tensor with the given shape.
Then in line 6, shape[1:] is (4, 3, 2), and shape[0] is 2, so zero_matrix((4, 3, 2)) is called 2 times in line 6, which creates a list of two 3-dimensional matrices. This list is returned and this is our matrix M.

Each call to zero_matrix((4, 3, 2)) returns a list of 4 matrices with shape (3, 2). Finally, each call
to zero_matrix((3,2)) returns a list of 3 matrices of shape (2,): here we are in the limit case where the
length of the shape tuple is 1, and a list of two 0's is returned in line 4 :)

Well done! I know it all about leap of faith with recursion happened. Your explanation is great, thanks again.

Alternative in native Python for nested lists as matrix is the dictionary with tuple key:

# python 2 or 3
import itertools

try:
    from pretty import ppr as pprint
except:
    from pprint import pprint

def zero_matrix(shape):
    return [zero_matrix(shape[1:])
            for i in range(shape[0])] if len(shape) > 1 else [0] * shape[0]

def zero_dict(shape):
# with dict:
    return dict([(tuple(values), 0) 
              for values in itertools.product(*(range(dimension) for dimension in shape))]) 
    

if __name__ == "__main__":
    M = zero_matrix((2, 4, 3, 2))
    pprint(M)
    print('-'*40)
    mdict = zero_dict((2,4,3,2))
    pprint(mdict)
    print len(mdict), 'values'

Line
print len(mdict), 'values'
does not work in Python 3, to make print which work in bot Python 2 and three without from __future__ import print_function, we can use

print("%i values" % len(mdict))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.