How to Retrieve an Entire Row or Column of an Array in Python?

Last Updated : 27 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Retrieving an entire row or column from an array in Python is a common operation, especially when working with matrices or tabular data. This can be done efficiently using different methods, especially with the help of NumPy. Let’s explore various ways to retrieve a full row or column from a 2D array.

Using numpy indexing

This is the most common and efficient method. NumPy allows you to use square brackets ([]) to slice rows and columns just like lists but with powerful features.

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

c = a[:, 2]
print(r,c)

Output
[4 5 6] [3 6 9]

Explanation: a[1] retrieves the second row and a[:, 2] extracts the third column by selecting all rows at column index 2.

Using np.take()

np.take() is a NumPy function that selects elements along a specific axis (rows or columns). It's helpful when you're dynamically selecting elements and want a bit more control.

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

r= np.take(a, indices=1, axis=0)
c = np.take(a, indices=2, axis=1)
print(r,c)

Output
[4 5 6] [3 6 9]

Explanation:

  • np.take(a, indices=1, axis=0) retrieves the second row (index 1) by selecting along rows (axis=0).
  • np.take(a, indices=2, axis=1) retrieves the third column (index 2) by selecting along columns (axis=1).

Using np.squeeze()

When you slice a specific row or column, NumPy may return it as a 2D array. np.squeeze() removes any unnecessary dimensions, giving you a clean 1D array.

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

c = np.squeeze(a[:, 2:3])
print(r, c)

Output
[4 5 6] [3 6 9]

Explanation:

  • a[1:2, :] gets the second row as a 2D array (1, 3), and np.squeeze() flattens it to [4, 5, 6].
  • a[:, 2:3] gets the third column as (3, 1) and np.squeeze() converts it to [3, 6, 9].

Using list comprehension

If you're not using NumPy or you're working with pure Python lists, you can manually loop through rows to get a specific column. It's slower and not recommended for large data, but it's good for understanding how things work under the hood.

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

c = [row[2] for row in a]
print(r, c)

Output
[np.int64(4), np.int64(5), np.int64(6)] [np.int64(3), np.int64(6), np.int64(9)]

Explanation:

  • list(a[1]) converts the second row to a regular Python list.
  • [row[2] for row in a] uses list comprehension to extract the third element from each row, forming the column.

Next Article
Article Tags :
Practice Tags :

Similar Reads