What is the numpy.ravel() function from NumPy in Python?

Overview

Python’s ravel() function is used to return a contiguous array. This function returns a 1D array that contains the input elements.

Syntax

The syntax for this function is as follows:

numpy.ravel(a, order='C')

Parameter value

The ravel() function takes the following parameter values:

  • a: This represents the input array.
  • order: This represents the type of order for the memory layout. This parameter value is optional. It can take a "C", "F", "A", or "K' order.

Return value

The ravel() function returns an array of the same subtype and shape as that of the input array a that is passed to it.

Code example

import numpy as np
# creating an array
myarray1 = np.array([[1, 2, 3], [4, 5, 6]])
# calling the ravel() function
myarray2 = np.ravel(myarray1, order = "K")
print(myarray2)
# checking the size of the imput and output arrays
print(myarray1.size)
print(myarray2.size)

Code explanation

  • Line 1: We import the numpy module.
  • Line 3: We create a 2D array called myarray1, using the array() function.
  • Line 6: We implement the ravel() function on the variable myarray1, using an order style K. We assign the result to another variable called myarray2.
  • Line 8: We print the array myarray2.
  • Lines 11–12: To confirm if both the input and output array are of the same size, we obtain and print their sizes with the array.size() function.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources