How To Print Columns Of The Matrix In Python

How To Print Columns Of The Matrix In Python? In this article, we will discuss how to print columns of the matrix in Python programming language. A matrix object is similar to nested lists as they are multi-dimensional. In Python,  a matrix is a rectangular Numpy array. The array has to be two-dimensional. It holds data held in the array’s rows and columns. 

Get A Column of the 2D Array in Python:

The 2D array mainly represents data in a tabular or two-dimensional format. Here we are going to discuss how to access a column of a 2D array, for this firstly we must create a 2D array with rows and columns. Then we can access the values of rows and columns using the index position. We can get the row value using the [ ] operator. We can get column value using [ ][ ].

# Creating a 2D array
array = [[23, 45, 43, 23, 45], [45, 67, 54, 32, 45],
         [89, 90, 87, 65, 44], [23, 45, 67, 32, 10]]

# display
print(array)

# get the first-row third element
print(array[0][2])

# get the third-row fourth element
print(array[2][3])

Output:-

[ [23, 45, 43, 23, 45], [45, 67, 54, 32, 45], [89, 90, 87, 65, 44], [23, 45, 67, 32, 10] ]
43
65

Extract Column in Array in Python

Here we are going to discuss how to extract a column in an array, for this firstly we must create an array with rows and columns. Then use the syntax [row[i] for row in array] to extract the i – indexed column from the array.

# Creating a 2D array
an_array = [[11, 12, 13],   [14, 15, 16],   [17, 18, 19]]
column_one = [row[1] for row in an_array]
print(column_one)

Output:-

[12, 15, 18]

So, here we have learned how to access the columns in the matrix in Python programming language. Hope you all find it useful.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *