v9.1.1
Menu

Flatten and Ravel Arrays

easyPROArray ManipulationNumPy Array ManipulationNumpy

Problem Statement

Convert a multi-dimensional array to 1D using flatten() and ravel().

Background

Both flatten() and ravel() convert arrays to 1D:

  • flatten(): Always returns a copy
  • ravel(): Returns a view when possible (more memory efficient)

Your Task

Write a function flatten_array(arr) that:

  1. Flattens the input array
  2. Returns a dictionary with:
    • "original_shape": Original shape as list
    • "flattened": Flattened array as list
    • "size": Total number of elements

Output Format

Return a dictionary with exactly these three keys.

Example

Input
[[1, 2, 3], [4, 5, 6]]
Output
{'original_shape': [2, 3], 'flattened': [1, 2, 3, 4, 5, 6], 'size': 6}
Reasoning
  • Input: a 2×32 \times 3 grid of integers, [[1, 2, 3], [4, 5, 6]] — 2 rows, each holding 3 values. Inputs may have any number of axes, e.g. a 2×2×22 \times 2 \times 2 cube.
  • Shape: record the length along each axis in order, rows first then columns, giving [2, 3]. One integer per axis.
  • Element count: the entry count is the product of the dimensions, 2×3=62 \times 3 = 6. For the cube it would be 2⋅2⋅2=82 \cdot 2 \cdot 2 = 8.
  • One-dimensional sequence: read the grid row by row, left to right — row 0 gives 1,2,31, 2, 3, then row 1 gives 4,5,64, 5, 6 — producing [1, 2, 3, 4, 5, 6]. Its length always equals the element count, 6.
  • Output: a dictionary with keys original_shape, flattened and size, holding those three results.
  • Notice that the shape is the only record of the grid's structure: the same six values could equally have been laid out as a 3×23 \times 2 or 1×61 \times 6 grid.

Constraints

  • Use flatten() or ravel()
  • Input can be any dimensional array

Learn this in

More from Numpy

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.