Search code examples
pythonmatrixrow

picking out rows and columns in matrix


In Python, I have defined my matrix the following way

A = [[1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19],
    [-2, 7, 4, 23]]

and wanted to try printing out the individual columns and rows by the following print(A[2][:]) and print(A[:][2]) for the 3rd row and 3rd column, respectively.

To my surprise, they both printed the 3rd row.

For the purpose of learning, I am not using Numpy or any math packages.

Not sure why print(A[2][:]) and print(A[:][2]) result in the same output


Solution

  • This seems to follow the same principles of accessing various elements in lists. Namely, by calling A[2] for example, you are calling the entire data in the 3rd element (which in this case is its own list). By further stating A[2][:] you are calling all elements within the 3rd list. The same logic is applied to the A[:][2] call - namely, all the information is called within your A list and then you further stipulate that you want the 3rd element shown - this is namely the 3rd 'sublist' so to say.