How can I index the first column of the 2nd and 3d row in the following matrix in Python?

Viewed 19

I've tried this

def matrix():
    A = [[0,1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    return(A[1:2][0])

I want the function to return the value 5 and 9

1 Answers

If you would like to get the first element of the 2nd and 3rd rows it is:

def matrix():
    A = [[0,1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    return (A[1][0], A[2][0])

This returns (5,9) as a tuple.

If you would like to parameterize it as such:

def matrix(rows):
    # rows is a tuple or array like (1,2) with the indexes
    A = [[0,1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    result = [] # empty list
    for i in rows:
        result.append(A[i][0])
    return result

After calling the method like this: matrix((1,2)), it returns [5,9] as a list.

Related