Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
communitycreator

What is the numpy.ndarray.flatten() method in Python?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The ndarray.flatten() method in Python is used to return a copy of a given array in such a way that it is collapsed into one dimension.

Syntax

ndarray.flatten(order='C')
Syntax for the ndarray.flatten() method

Parameter value

The ndarray.flatten() method takes an optional parameter value, orfer, which represents the order to which the array is to be flattened. The different orders are:

  • 'C': This is to flatten the array in row-major order.
  • 'F': This is to flatten the array in column-major order.
  • 'A': This is to flatten the array in column-major order, if the input array is Fortran contiguous in memory, and row-major order if otherwise.
  • 'K': This is to flatten the array in the order in which its elements occur in memory.

The default value is 'C'.

Example

import numpy as np
# creating an input array
myarray = np.array([[1,2,3],[4,5,6]])
# to flatten the array in F-order
print(myarray.flatten('F'))
Implementing the ndarray.flatten() method

Code explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array, myarray , using the array() function.
  • Line 6: We implement the ndarray.flatten() method on the input array. We print the result to the console.

RELATED TAGS

numpy
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring