Convert list of list to array

We can use numpy ndarray tolist[] function to convert the array to a list. If the array is multi-dimensional, a nested list is returned. For one-dimensional array, a list with the array elements is returned.

NumPy Array to List

The tolist[] function doesnt accept any argument. Its a simple way to convert an array to a list representation.

1. Converting one-dimensional NumPy Array to List

import numpy as np # 1d array to list arr = np.array[[1, 2, 3]] print[f'NumPy Array:\n{arr}'] list1 = arr.tolist[] print[f'List: {list1}']

Output:

NumPy Array: [1 2 3] List: [1, 2, 3]

2. Converting multi-dimensional NumPy Array to List

import numpy as np # 2d array to list arr = np.array[[[1, 2, 3], [4, 5, 6]]] print[f'NumPy Array:\n{arr}'] list1 = arr.tolist[] print[f'List: {list1}']

Output:

NumPy Array: [[1 2 3] [4 5 6]] List: [[1, 2, 3], [4, 5, 6]]

Reference: API Doc

Video liên quan

Chủ Đề