How to convert a list of lists into a Python NumPy array?

Sometimes, we want to convert a list of lists into a Python NumPy array.

In this article, we’ll look at how to convert a list of lists into a Python NumPy array.

How to convert a list of lists into a Python NumPy array?

To convert a list of lists into a Python NumPy array, we can create an array of arrays with the numpy.array method.

For instance, we write:

import numpy

x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array([numpy.array(xi) for xi in x], dtype=object)
print(y)

We call numpy.array with a list that converts the lists inside x to array with numpy.array(xi) for xi in x.

And we set dtype to object.

As a result, we see that y is [array([1, 2]) array([1, 2, 3]) array([1])].

Conclusion

To convert a list of lists into a Python NumPy array, we can create an array of arrays with the numpy.array method.