Wednesday, July 8, 2026
HomeLanguagesConvert Python Nested Lists to Multidimensional NumPy Arrays

Convert Python Nested Lists to Multidimensional NumPy Arrays

Prerequisite: Python List, Numpy ndarray

Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists.

Method 1: Using numpy.array().

Approach :

  • Import numpy package.
  • Initialize the nested list and then use numpy.array() function to convert the list to an array and store it in a different object.
  • Display both list and NumPy array and observe the difference.

Below is the implementation.

Python3




# importing numpy library
import numpy
 
# initializing list
ls = [[1, 7, 0],
       [ 6, 2, 5]]
 
# converting list to array
ar = numpy.array(ls)
 
# displaying list
print ( ls)
 
# displaying array
print ( ar)


Output :

[[1, 7, 0], [6, 2, 5]]
[[1 7 0]
 [6 2 5]]

Method 2: Using numpy.asarray().

Approach :

  • Import numpy package.
  • Initialize the nested 4-dimensional list and then use numpy.asarray() function to convert the list to the array and store it in a different object.
  • Display both list and NumPy array and observe the difference.

Below is the implementation.

Python3




# importing numpy library
import numpy
 
# initializing list
ls = [[1, 7, 0],[ 6, 2, 5],[ 7, 8, 9],[ 41, 10, 20]]
 
# converting list to array
ar = numpy.asarray(ls)
 
# displaying list
print ( ls)
 
# displaying array
print ( ar)


Output :

[[1, 7, 0], [6, 2, 5], [7, 8, 9], [41, 10, 20]]
[[ 1  7  0]
 [ 6  2  5]
 [ 7  8  9]
 [41 10 20]]
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32519 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12016 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7263 POSTS0 COMMENTS
Thapelo Manthata
6977 POSTS0 COMMENTS
Umr Jansen
6968 POSTS0 COMMENTS