Convert List to Numpy Array


Convert List to Numpy Array

To convert a List into Numpy Array in Python, call numpy.array() function and pass the list as argument to this function.

The syntax to call numpy.array() to convert a list into numpy array is

numpy.array(x)

where x is a list.

Return Value

numpy.array() returns a numpy array of type numpy.ndarray.

Examples

1. Convert a list of numbers to a numpy array

In this example, we take a list in x, and convert this list into numpy array using numpy.array().

Python Program

import numpy

x = list([1, 2, 4, 8, 16, 32])
arr = numpy.array(x)

print("List :", x)
print("Numpy Array :", arr)

Output

List : [1, 2, 4, 8, 16, 32]
Numpy Array : [ 1  2  4  8 16 32]

2. Convert a list of lists to a numpy array

In this example, we take a list of lists in x, and convert this list into numpy array using numpy.array().

Python Program

import numpy

x = list([[1, 2, 4], [8, 16, 32]])
arr = numpy.array(x)

print("List :", x)
print("Numpy Array :", arr)

Output

List : [[1, 2, 4], [8, 16, 32]]
Numpy Array : [[ 1  2  4]
 [ 8 16 32]]

Since, there are two levels of lists, we get a two-dimensional numpy array.

Summary

In this Numpy Tutorial, we learned how to convert a list into a numpy array, with the help of syntax and examples.