Python

# Convert Python Numpy Array to List

By ayed_amira , on 05/01/2020 , updated on 09/10/2020 - 3 minutes to read Numpy Array to List : In this part, we will see how to convert a numpy array into a list using the numpy library present in python.

## NumPy Array to List – to_list() function

The numpy library contains a function to convert an array to a list called to_list()

This function ndarray.tolist() returns the table in list form. It can be nested according to the format of the array. It returns a copy of the data from the array as a Python list (nested subform). The data elements are converted to the closest compatible Python type to the array.

This function does not take any parameter, it is very simple to use as we will see in the examples below.

### One-dimensional NumPy Array

The first thing we’re going to see is converting an array to 1-dimensional:

```import numpy as np

# Declare numpy Array

print(f'NumPy Array:\n{data}')

list = data.tolist()
print(f'List: {list}')

```

The syntax is very simple and easy to use. In our example we have declared a numpy array which we called “data”. To this object, we call the to_list function which will convert this numpy array into a one dimensional list.

### Multi-dimensional NumPy Array

In some use cases, we need to define numpy arrays that contain multiple dimensions. The to_list() function also allows us to convert this kind of array. In these examples we will declare an array with 2 and then 3 dimensions to see the corresponding results:

```import numpy as np

# Declare numpy Array

data2dim = np.array([[1, "AMIRADATA", 2],[4, "PYTHON",5,6]])
print(f'NumPy Array:\n{data2dim}')
data3dim = np.array([[1, "AMIRADATA", 2],[4, "PYTHON",5,6],[7,8]])
print(f'NumPy Array:\n{data3dim}')

list2 = data2dim.tolist()
print(f'List 2 dimensions: {list2}')
list3 = data3dim.tolist()
print(f'List 3 dimensions: {list3}')

```

Output :

NumPy Array:
[list([1, ‘AMIRADATA’, 2]) list([4, ‘PYTHON’, 5, 6])]
NumPy Array:
[list([1, ‘AMIRADATA’, 2]) list([4, ‘PYTHON’, 5, 6]) list([7, 8])]
List 2 dimensions: [[1, ‘AMIRADATA’, 2], [4, ‘PYTHON’, 5, 6]]
List 3 dimensions: [[1, ‘AMIRADATA’, 2], [4, ‘PYTHON’, 5, 6], [7, 8]]

We can have as many dimensions as we wish according to our needs.

I have nothing more to add in the explanations of this function which is very easy to use! 🙂 I hope this has allowed you to learn a bit more about using numpy. The best way to learn will always remain to practice! So I invite you to practice on your own use cases ! 🙂

For people interested in data science, I share with you this book that presents the main tools to work in this field and of course the numPY bookstore is present in this book! (As an Amazon Partner, I make a profit on qualifying purchases)

Find all the articles talking about python here :