*33*

You can use the following basic syntax to convert a list in Python to a NumPy array:

import numpy as np my_list = [1, 2, 3, 4, 5] my_array = np.asarray(my_list)

The following examples shows how to use this syntax in practice.

**Example 1: Convert List to NumPy Array**

The following code shows how to convert a list in Python to a NumPy array:

import numpy as np #create list of values my_list = [3, 4, 4, 5, 7, 8, 12, 14, 14, 16, 19] #convert list to NumPy array my_array = np.asarray(my_list) #view NumPy array print(my_array) [ 3 4 4 5 7 8 12 14 14 16 19] #view object type type(my_array) numpy.ndarray

Note that you can also use the **dtype** argument to specify a certain data type for the new NumPy array when performing the conversion:

import numpy as np #create list of values my_list = [3, 4, 4, 5, 7, 8, 12, 14, 14, 16, 19] #convert list to NumPy array my_array = np.asarray(my_list, dtype=np.float64) #view data type of NumPy array print(my_array.dtype) float64

**Example 2: Convert List of Lists to NumPy Array of Arrays**

The following code shows how to convert a list of lists to a NumPy array of arrays:

import numpy as np #create list of lists my_list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] #convert list to NumPy array my_array = np.asarray(my_list_of_lists) #view NumPy array print(my_array) [[1 2 3] [4 5 6] [7 8 9]]

We can then use the **shape** function to quickly get the dimensions of the new array of arrays:

print(my_array.shape) (3, 3)

This tells us that the NumPy array of arrays has three rows and three columns.

**Additional Resources**

The following tutorials explain how to perform other common data conversions in Python:

How to Convert a List to a DataFrame in Python

How to Convert a List to a DataFrame Row in Python

How to Convert Pandas Series to DataFrame

How to Convert Pandas Series to NumPy Array