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

Time:04-28

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.

CodePudding user response:

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]

If you also want to set values, you can use zip twice:

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

Output:

[(1, 69, 3), (4, 69, 6), (7, 69, 9)]
  • Related