Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Flattening transforms a multi-dimensional array (2D matrix, 3D image tensor, or higher-order volume) into a continuous, 1-dimensional array. This operation is ubiquitous before feeding image pixels into dense neural network layers, computing histograms, or serializing data.
NumPy provides two primary methods for this operation:
arr.ravel()arr.flatten()While both methods return a 1D array with identical elements, their memory allocation mechanics and performance profiles are fundamentally different.
+---------------+---------------------+-----------------------+--------------------+ | Method | Memory Allocation | Modifies Original? | Speed Performance | +---------------+---------------------+-----------------------+--------------------+ | arr.ravel() | VIEW (when possible)| YES (in-place linked) | Blazing fast (0 ms)| | arr.flatten() | COPY (always) | NO (completely safe) | Slower (allocates) | +---------------+---------------------+-----------------------+--------------------+
ravel(): Zero-Copy Flatteningravel() inspects the memory strides of the array. If the array is contiguous, it creates a new 1D array header pointing directly to the existing data buffer without allocating or copying any memory:
Output:
flatten(): Safe Copy Allocationflatten() is a method of ndarray that always allocates fresh memory and copies every element into the new buffer:
Output:
ravel() Fall Back to a Copy?If an array has non-contiguous memory layout—such as after a transpose or step-sliced indexing—it is mathematically impossible to represent a flattened version with a single uniform 1D stride. In that case, ravel() automatically allocates a copy:
Both methods accept the order parameter:
'C': Flatten row-by-row (default).'F': Flatten column-by-column.arr.ravel() and arr.flatten()?b = a.flatten(); b[0] = 100, what happens to a[0, 0]?arr.ravel() return a copy instead of a view?np.ravel(a) or np.flatten(a)?np.array([[10, 20], [30, 40]]).ravel(order='F')?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.