How To Convert a NumPy Array to List in Python?

How To Convert a NumPy Array to List in Python?

In NumPy, you can convert np.array objects to a regular Python list using the list () function. This function takes no arguments. If the array is one-dimensional, it returns a list containing the array elements. For multi-dimensional arrays, it returns a nested list.

Prerequisites

To finish this tutorial, you’ll require:

You should be familiar with installing Python 3 and using pip to install packages. Additionally, having some experience with coding in Python is necessary for this tutorial.

Converting one-dimensional NumPy Array to List

Let’s create a simple one-dimensional array with the values [‘a’, ‘b’, ‘c’]:

Example

import numpy as np
# one-dimensional array to list
simple_arr = np.array(['a', 'b', 'c'])
print(f'NumPy Array is:\n{simple_arr}')

Output

NumPy Array is:
['a', 'b', 'c']

Now, let’s utilize the to list() function:

Save $100 in the next
5:00 minutes?

Register Here

Example

import numpy as np
# one-dimensional array to list
simple_arr = np.array(['a', 'b', 'c'])
print(f'NumPy Array is:\n{simple_arr}')
simple_list = simple_arr.tolist()
print(f'List is:\n{simple_list}')

Output

NumPy Array is:
['a' 'b' 'c']
List is:
['a', 'b', 'c']

The array has been transformed from NumPy scalars to Python scalars.

Converting multi-dimensional NumPy Array to List

Let’s create a two-dimensional array with the values [[‘a’,’b’, ‘c’], [‘d’, ‘e’, ‘f’]]:

Example

import numpy as np
# multi-dimensional array to list
multi_arr = np.array([['a','b', 'c'], ['d', 'e', 'f']])
print(f'NumPy Array with multi-dimensional:\n{multi_arr}')

Output

NumPy Array with multi-dimensional:
[['a' 'b' 'c']
 ['d' 'e' 'f']]

Now, let’s utilize the to list() function:

Example

import numpy as np
# multi-dimensional array to list
multi_arr = np.array([['a', 'b' ,'c'],['d' ,'e', 'f']])
print(f'NumPy Array with multi-dimensional:\n{multi_arr}')
multi_list = multi_arr.tolist()
print(f'\n List list:\n{multi_list}')

Output

NumPy Array with multi-dimensional:
[['a' 'b' 'c']
 ['d' 'e' 'f']]
 List list:
[['a', 'b', 'c'], ['d', 'e', 'f']]

The array has been transformed from NumPy scalars to Python scalars.

Conclusion

In this article, you’ve learned to use tolist() to convert np.array objects to lists. This method applies to both one-dimensional and multi-dimensional arrays. Following this article, you can also learn to add elements to a list in Python.

Save $100 in the next
5:00 minutes?

Register Here