25.5 C
London
Thursday, June 19, 2025
HomePandas in PythonDataFrame Functions in PythonHow to Convert List to NumPy Array (With Examples)

How to Convert List to NumPy Array (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories