Python | Get Kth Column of Matrix
In this article, we will discuss how to extract the Kth column from a matrix in Python.
Example:
Matrix = [[4, 5, 6],
[8, 1, 10],
[7, 12, 5]]
The 2nd column (K=2, 0-indexed) would be [6, 10, 5].
Let's look at the different methods below to do it in Python:
Using NumPy
NumPy is a high-performance library for numerical computations. Converting a list of lists into a NumPy array allows vectorized operations, which are faster and more memory-efficient compared to Python loops.
import numpy as np
mat = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
K = 2
res = np.array(mat)[:, K]
print(res)
Output
[ 6 10 5]
Explanation:
- np.array(mat): Converts a list of lists into a NumPy array for efficient operations.
- [:, K]: Selects all rows (:) and only the Kth column (K).
Using List Comprehension
Iterates over each row and picks the Kth element. This is clean, Pythonic, and memory-efficient.
mat = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
K = 2
res = [row[K] for row in mat]
print( res)
Output
[6, 10, 5]
Explanation:
- List comprehension: Iterates over each row in matrix.
- row[K]: Extracts the Kth element from each row.
Using map()
Applies a lambda function to extract the Kth element from each row. The map() function is slightly less intuitive but works efficiently.
mat = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
K = 2
res = list(map(lambda row: row[K], mat))
print( res)
Output
[6, 10, 5]
Explanation:
- map(): Applies a function to each element of matrix (each row).
- lambda row: row[K]: Anonymous function that extracts the Kth element from a row.
- list(): Converts the map object into a list.
Using zip()
Transposes the matrix with zip(*) and selects the Kth row of the transposed matrix. This method is readable but slightly slower due to creating intermediate tuples.
mat = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
K = 2
res = list(zip(*mat))[K]
print( res)
Output
(6, 10, 5)
Explanation:
- *mat: Unpacks the matrix rows as separate arguments.
- zip(*mat): Transposes the matrix, converting rows into columns.
- [K]: Selects the Kth column from the transposed result.
- list(): Converts the resulting tuple of elements into a list.
Using a For Loop
Manually iterates through each row, appending the Kth element to a new list. This is simple and beginner-friendly but verbose.
mat = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
K = 2
res = []
for row in mat:
res.append(row[K])
print( res)
Output
[6, 10, 5]
Explanation:
- for row in mat: Iterates over each row of the matrix.
- row[K]: Accesses the element at index K in the current row (the Kth column element).
- res.append(row[K]): Adds this element to the result list res.
- res: Contains all elements from the Kth column after the loop.