Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print a column of a matrix(2D list) in python without a loop?

To print the 2nd row I do like this
print(coeff_matrix[2])

to my surprise
print(coeff_matrix[:][2])
prints the 2nd row as well , not the 2nd column as I was expecting.
Why is it so and what is the correct way to print 2nd column.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert coefficient_matrix to a numpy array and use slicing:

import numpy as np
a = np.array([[1,2,3], [4, 5, 6], [7,8, 9]])
a[:,1]

Output:

array([2, 5, 8])

If numpy is not available, you can use zip:

a = [[1,2,3], [4, 5, 6], [7,8, 9]]
list(zip(*a))[1]

Output:

(2, 5, 8)

Or list comprehension (if that counts as without a loop?):

[i[1] for i in a]

Output:

[2, 5, 8]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading