How to index into nested lists?

Think of it as a list of lists rather than a “matrix”, and the logic becomes more obvious. Matrix m has two elements: m[0] = [1, 2, 3] and m[1] = [4, 5, 6]. So accessing a single value from within those lists requires another index. For example, m[0][1] = 2.

def matrix(m, a, b):
    return m[a][b] # element b from list a in list m

If you really want to use a matrix, consider numpy.

Leave a Comment