![]() |
VOOZH | about |
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:
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.
[ 6 10 5]
Explanation:
Iterates over each row and picks the Kth element. This is clean, Pythonic, and memory-efficient.
[6, 10, 5]
Explanation:
Applies a lambda function to extract the Kth element from each row. The map() function is slightly less intuitive but works efficiently.
[6, 10, 5]
Explanation:
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.
(6, 10, 5)
Explanation:
Manually iterates through each row, appending the Kth element to a new list. This is simple and beginner-friendly but verbose.
[6, 10, 5]
Explanation: