How to convert list to numpy array in python

Photo by olia danilevich from Pexels

In this tutorial, I will show you how to convert a list to a numpy array in python.

The first thing we need to do is import the numpy module. This module is used for scientific computing and it has a lot of useful functions for data analysis.

import numpy as np

convert list to numpy array

listData = [1, 2, 3]
npArrData = np.asarray(listData)
print("listData:", type(listData), ": ", listData)
print("npArrData: ", type(npArrData), ": ", npArrData)
# Output
# listData: <class 'list'> : [1, 2, 3]
# npArrData: <class 'numpy.ndarray'> : [1 2 3]

convert numpy array to list

npArrData = np.array([1, 2, 3])
listData = npArrData.tolist()
print("npArrData: ", type(npArrData), ": ", npArrData)
print("listData:", type(listData), ": ", listData)
# Output
# npArrData: <class 'numpy.ndarray'> : [1 2 3]
# listData: <class 'list'> : [1, 2, 3]

Thank you for reading & enjoy your coding πŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s