Home »
Python »
Python Programs
How to get a contiguous array in NumPy?
Learn, how to get a contiguous array in Python NumPy?
Submitted by Pranit Sharma, on March 09, 2023
Getting a contiguous array in NumPy
A contiguous array type is a specialized array that always stores its elements in a contiguous region of memory.
To get a contiguous array in numpy, we use numpy.ascontiguousarray() which returns a contiguous array (ndim >= 1) in memory (C order).
Syntax
numpy.ascontiguousarray(a, dtype=None, *, like=None)
Parameter(s)
- a: input array
- dtype: data type of returned array, can be str or dtype object.
- like: Reference object to allow the creation of arrays which are not NumPy arrays.
Let us understand with the help of an example,
Python code to get a contiguous array in NumPy
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.ones((2, 3), order='F')
# Display original array
print("Original Array:\n",arr,"\n")
# Creating a contiguous array
res = np.ascontiguousarray(arr)
# Display result
print("append result:\n",res,"\n")
# Check if res is contiguous or not
print("Is res contiguous:\n",res.flags['C_CONTIGUOUS'])
Output
Python NumPy Programs »