NumPy flatten()

The flatten() method flattens a NumPy array without changing its data.

Here, array1 is a two-dimensional array that is flattened to a one-dimensional array with all its elements intact.


flatten() Syntax

The syntax of flatten() is:

ndarray.flatten(order)

flatten() Argument

The flatten() method takes one argument:

  • order (optional) - specifies the order in which the array elements are flattened

flatten() Return Value

The flatten() method returns the flattened one-dimensional array.


Example 1: Flatten a Multidimensional Array

Output

 [0 1 2 3 4 5 6 7]

Specify order to Flatten an Array

We can flatten the array elements in any order by passing the order argument.

The order can be:

  • 'C' - flattens the elements row-wise (in C-style order)
  • 'F' - flattens the elements column-wise (in Fortran-style order)
  • 'A' - tries to preserve the original array's order, otherwise defaults to C-order.
  • 'K' - flattens the elements in the order they occur in memory, uses C-order by default.

Output

C: [0 1 2 3 4 5 6 7]
F: [0 4 2 6 1 5 3 7]
A: [0 1 2 3 4 5 6 7]
K: [0 4 2 6 1 5 3 7]

Difference Between Flatten and Ravel

The key differences between flatten() and ravel() are

  • flatten() is an ndarray object method whereas ravel() is a library-level function. For example,

Output

[1 2 3 4]
[1 2 3 4]
  • ravel() works with a list of arrays, but flatten() doesn't.

Output

[1 2 3 4]
Traceback (most recent call last):
  File "<string>", line 13, in <module>
ERROR!
AttributeError: 'list' object has no attribute 'flatten'
  • flatten() always returns a copy of the original array whereas ravel() makes a copy only when necessary.

To learn more, visit NumPy ravel().