Returning a NumPy Array as an Evaluatable String with array_repr()

Page content

Simply Printing a NumPy Array

When you simply print a NumPy array, it looks like this:

>>> import numpy as np
>>> a = np.arange(12).reshape(3, 4)
>>> print(a)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

This is easy to read, but since the elements are not separated by commas, you cannot copy and paste this output into another code to use it as a constant.

numpy.array_repr

There is a function called numpy.array_repr() that returns an evaluatable string, and when you use it, you get the following:

>>> print(np.array_repr(a))
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

You can copy and paste this, add np. or so, and then use it as a constant in another code.

Of course, you could also output it to a file like .npy, but this method is more convenient if the array size is small.

https://numpy.org/doc/stable/reference/generated/numpy.array_repr.html