Convert numpy.ndarray and list to each other
The NumPy array numpy.ndarray and the Python built-in type list can be converted to each other.
- Convert list to numpy.ndarray: numpy.array[]
- Convert numpy.ndarray to list: tolist[]
For convenience, the term "convert" is used, but in reality, a new object is generated while keeping the original object.
Convert list to numpy.ndarray: numpy.array[]
By passing list to numpy.array[], numpy.ndarray is generated based on it.
The data type dtype of generated numpy.ndarray is automatically determined from the original list, but can also be specified with the argument dtype.
See the following article for more information about the data type dtype in NumPy.
- NumPy: Cast ndarray to a specific dtype with astype[]
The same applies to multi-dimensional arrays of two or more dimensions.
Multi-dimensional list are just nested list [list of list], so it doesn't matter if the number of elements in the list doesn't match.
However, passing it to numpy.array[] creates numpy.ndarray whose elements are built-in list.
Note that missing elements cannot be filled.
Convert numpy.ndarray to list: tolist[]
The method tolist[] of numpy.ndarray returns list.
Depending on the number of dimensions of the original numpy.ndarray, a nested list is generated. Each element can be accessed by repeating the index [n].
1D:
2D:
3D:
Related Categories
- Python
- NumPy
- List
Related Articles
- Convert 1D array to 2D array in Python [numpy.ndarray, list]
- Remove / extract duplicate elements from list in Python
- NumPy: Remove rows / columns with missing value [NaN] in ndarray
- numpy.delete[]: Delete rows and columns of ndarray
- NumPy: Arrange ndarray in tiles with np.tile[]
- Convert a list of strings and a list of numbers to each other in Python
- Count elements from a list with collections.Counter in Python
- Alpha blending and masking of images with Python, OpenCV, NumPy
- Pretty-print with pprint in Python
- NumPy: Rotate array [np.rot90]
- Image processing with Python, NumPy
- Generate gradient image with Python, NumPy
- Extract, replace, convert elements of a list in Python
- NumPy: Slicing ndarray
- NumPy: How to use reshape[] and the meaning of -1