# Demystifying Python Numpy Array Tolist

The following article will discuss the NumPy array and how we can convert it to a standard python list. The NumPy module provides functions that help us achieve this.

A NumPy array consists of a grid of values of a similar type. The indexing in a NumPy array is done using non-negative integer values. The dimension of an array is considered to be its “rank.” An array shape is determined by the number of elements along each dimension of the array.

Contents

The Python NumPy module provides us with packages for array processing. It allows us to create “array objects” of multiple dimensions. Various functions for manipulating these array objects are also provided within the module. It is the most fundamental library for scientific computation in Python.

The function provides us with a list of all the data elements from the NumPy array.

Syntax`arrayName.tolist()`
Parameters – NONE
Return – A nested list consisting of the array elements

## How To Convert a NumPy Array to a Python List

### One Dimensional Array

In this program, we are passing the `tolist` function to a one-dimensional NumPy array.

```import numpy as np
myArray = np.array([3,2,5,9])
print(myArray)
print(type(myArray))

#converting to a list

arrList = myArray.tolist()

print(arrList)

# type of arrList
print(type(arrList))
```

Output

```[3 2 5 9]
<class 'numpy.ndarray'>
[3, 2, 5, 9]
<class 'list'>```

### Two Dimensional Array

Similar to the previous example, we will pass a two-dimensional NumPy array in this demonstration.

```import numpy as np
myArray = np.array([[3,2,5],
[4,4,3],
[9,5,6]])
print(myArray)
print(type(myArray))

#converting to a list

arrList = myArray.tolist()

print(arrList)

# type of arrList
print(type(arrList))
```

Output

```[[3 2 5]
[4 4 3]
[9 5 6]]
<class 'numpy.ndarray'>
[[3, 2, 5], [4, 4, 3], [9, 5, 6]]
<class 'list'>```

## Passing NumPy Array tolist Function Over a 2nd Axis

Let’s look at how we can split an n-dimensional NumPy array within an internal axis.

Consider an array of shape (3,133,78,78,78,1) within a list of 150 arrays. In order to retrieve a list based on an internal axis, let’s pass the `.swapaxes` function.

The `swapaxes()` function allows us to interchange two or more axes of an array in Python.

So we should pass: np.swapaxes(nameofArray,0,1) and place the 150 dimensions in the beginning. Furthermore, `list()` can be passed to retrieve the complete list

## Appending NumPy Array to a List

The following demonstration shows us how we can append NumPy Arrays to a Python List.

```import numpy as np
a = np.empty((3), int)

listINIT = []
for idx in range(4):
for i in range(3):
a[i] = idx*10 + i
print("idx =",idx,"; a =",a)
listINIT.append(a.copy())

print("listINIT =",listINIT)
```

Output

## How To Convert a 2D NumPy Array to a List of Lists using tolist?

Let’s look at how we can convert a 2D array into nested lists.

For this procedure, we will primarily be using the Numpy array tolist function.

```import numpy as np
myArray = np.array([[3, 6, 9, 12],
[56, 63, 12, 77],
[12, 32, 12, 2]])
print(myArray)
listOfList = myArray.tolist()
print(listOfList)
```

Output

```[[ 3  6  9 12]
[56 63 12 77]
[12 32 12  2]]
[[3, 6, 9, 12], [56, 63, 12, 77], [12, 32, 12, 2]]```

## How To Convert N-Dimensional NumPy Array To a List of Tuples?

In this program, we will see how we can convert multiple dimensional arrays into a List of Tuples.

```import numpy as np
myArray = np.array([[[3,12]],
[[56, 77]]])

# Converting to a list of tuples my reshaping myArray
list(map(tuple, myArray.reshape((2, 2))))

```

Output

`[(3, 12), (56, 77)]`

## How To Display Arrays Without The Square Brackets

We can display the elements alone within an array by excluding the square brackets. Let’s how that’s achieved in One and Two Dimensional Arrays.

### 1D Arrays

```import numpy as np
myArray = np.array([3,5,6])
print(*myArray, sep=', ')
```

Output

`3, 5, 6`

### 2D Arrays

Implementing the same program as the 1D array will only remove the outermost brackets. Therefore, let’s look at a different program.

```import numpy as np
myArray = np.array([[3,5,6],
[8,2,3],
[9, 82, 0]])
print(str(myArray).replace(' [', '').replace('[', '').replace(']', ''))
```

Output

``` 3  5  6
8  2  3
9 82  0```

## Flattening a List of NumPy Arrays

Using the `numpy.contactenate` function, we can concatenate elements from an input list into a single array object.

```import numpy as np
contactElem = np.concatenate(input_list).ravel()
```

The final output can be displayed in a list format like so:

```import numpy as np
contactElemList = np.concatenate(input_list).ravel().tolist()
```

## Converting Multidimensional Arrays into Lists of Lists

We can use the `.tolist()` function to convert NumPy matrices to lists.

Let’s look at the following demonstration:

```import numpy as np
myArray = np.array([[3,5,6],
[8,2,3],
[9, 82, 0]])
listArray = myArray.tolist()
type(listArray)
print(listArray)
```

Output

`[[3, 5, 6], [8, 2, 3], [9, 82, 0]]`

## FAQs

What is the time complexity of tolist?

The time complexity for `.tolist()` is O(n), where n is the number of elements in the list.

Is Python List faster than NumPy Array?

NumPy Arrays are faster than Python Lists. This is due to the fact that an array consists of elements of similar types in adjacent memory locations. At the same time, List elements can be of different types located in non-adjacent memory locations.

## Conclusion

In this article, we have looked at the versatility of NumPy arrays and how they differ from regular Python lists. We have demonstrated the use cases for NumPy array tolist and various scenarios where the function comes in handy.

Subscribe
Notify of 