Table of contents
1.
Introduction
2.
Understanding np.flatten()
2.1.
Definition and Purpose
2.2.
Syntax
2.3.
Example
2.4.
Python
3.
Understanding np.ravel()
3.1.
Definition and Purpose
3.2.
Syntax
3.3.
Example
3.4.
Python
4.
Key Differences Between np.flatten() and np.ravel() 
5.
Frequently Asked Questions
5.1.
When should I use np.flatten()?
5.2.
When should I use np.ravel()?
5.3.
How do np.flatten() and np.ravel() handle multidimensional arrays?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference Between Flatten and Ravel Functions in Numpy

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When working with data in Python, especially with arrays and matrices, the NumPy library offers helpful functions to manipulate and reshape the data. Two such functions are np.flatten() and np.ravel(). These functions might seem similar at first glance, but they have some distinct differences that are important to understand. In this guide, we will explore the dissimilarities between these functions, helping you choose the right one for your specific needs.

Difference Between Flatten and Ravel Functions in Numpy

Let's deep dive into the world of np.flatten() and np.ravel() to uncover their unique traits and learn when to use each one effectively.

Understanding np.flatten()

Imagine you have a bunch of colorful beads arranged in rows and columns. Flattening is like taking all those beads and putting them in a single straight line. This way, you can count them easily one by one, without worrying about their original arrangement. It's like turning a grid of beads into a simple necklace.

Definition and Purpose

np.flatten() is a function provided by the NumPy library in Python that takes a multi-dimensional array as input and returns a one-dimensional array. It reshapes the input array by arranging all its elements sequentially in a linear order, disregarding the original structure of dimensions. This transformation simplifies the data representation, making it more accessible for certain types of calculations and processing while preserving the original array unchanged. 

The purpose is to simplify complex data structures, making it easier to perform certain operations that require a linear sequence of values. By arranging the array elements in a linear order, np.flatten() facilitates calculations and analyses that are more straightforward with a simpler data layout.

Syntax

The syntax for using np.flatten() looks like this:

flattened_array = np.flatten(original_array)


Here, original_array is the multi-dimensional array you want to flatten. When you call np.flatten() on this array, it creates a new one-dimensional array called flattened_array.

Example

Let’s discuss an example illustrating np.flatten().

Code

  • Python

Python

import numpy as np

# Create a multi-dimensional array
input_array = np.array([[10, 20], [30,40], [50,60]])

# Use np.flatten() to flatten the array
flattened_array = input_array.flatten()

# Print the original and flattened arrays
print("Original Array : \n")
print(input_array)

print("Flattened Array:")
print(flattened_array)
You can also try this code with Online Python Compiler
Run Code

 

Output

output

Explanation

  1. We start by importing a Python library called NumPy, which helps us work with arrays and matrices.
     
  2. We create a 2-dimensional array called original_array. It's like a grid of numbers with three rows and three columns.
     
  3. We use the np.flatten() function from NumPy to make the 2D array into a 1D array. This means we're turning the grid into a simple list of numbers.
     
  4. Finally, we print both the original 2D array and the flattened 1D array to see the difference.

Understanding np.ravel()

Think of your data as a big grid of numbers, like a chessboard. Sometimes, you want to read all the numbers in a straight line, row by row, instead of going back and forth like a chess piece. That's where np.ravel() comes in.

It takes this grid of numbers with rows and columns and makes a simple list by reading all the numbers in a straight line. This list lets you easily check each number one by one, without worrying about the original rows and columns. It's like converting a chessboard into a line of numbers without changing the numbers themselves

Definition and Purpose

np.ravel() is a function provided by the NumPy library in Python, used to convert a multi-dimensional array into a one-dimensional array. Unlike np.flatten(), which creates a new array, np.ravel() returns a flattened view of the original array. This means that any changes made to the flattened view will also affect the original array. It's a way to access and work with the elements of a multi-dimensional array in a linear sequence without altering its underlying structure.

The purpose of the np.ravel() function in NumPy is to provide a flattened view of a multi-dimensional array. This view retains the original data in a linear order, enabling efficient access and manipulation of array elements without altering the array's underlying structure. 

Syntax

The syntax of np.ravel() is as follows:

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


Here's what this means:

  • numpy: This is the name of the module (library) we're using. In this case, it's NumPy.
     
  • ravel(): This is the function we're calling, which stands for "ravel." It's like saying "flatten" or "unroll."
     

The function takes two main arguments:

  • a: This is the array that you want to flatten or make one-dimensional.
     
  • order: This argument is optional. It specifies the order in which the elements of the flattened array will be arranged. The default is 'C', which stands for C-style order (row-major order). The other option is 'F', which stands for Fortran-style order (column-major order).

Example

Let’s discuss an example illustrating np.ravel().

Code

  • Python

Python

import numpy as np

# Creating a multi-dimensional array
my_array = np.array([[10, 20], [30,40], [50,60]])
flattened = np.ravel(my_array)

# Display the original and flattened arrays
print("Input Array : \n")
print(my_array)

print("Flattened Array : ")
print(flattened)
You can also try this code with Online Python Compiler
Run Code

 

Output

output

Explanation

  1. We start by importing a Python library called NumPy, which is very useful for working with arrays and matrices.
     
  2. We create a 2-dimensional array called my_array with three rows and two columns. It's like a table of numbers.
     
  3. Then, we use the np.ravel() function from NumPy to "flatten" the array. This means we're turning the 2D table into a 1D list.
     
  4. Finally, we print both the original my_array and the flattened version called flattened.

 

So, the code creates a table of numbers, flattens it into a simple list, and shows both the original and flattened versions to us.

Key Differences Between np.flatten() and np.ravel() 

Let’s discuss the difference between np.flatten() and np.ravel().

Aspect

np.flatten()

np.ravel()

 

Definition

np.flatten() takes a multi-dimensional array and creates a new one-dimensional array by copying all elements. np.ravel() also transforms a multi-dimensional array into a one-dimensional array, either by creating a new array or providing a view, depending on memory efficiency.
Modification of Original Array Does not modify the original array ie, creates a copy. Doesn't modify the original array.
New Array Creation Creates a new copy of the array's elements. Creates a new array or returns a view of the existing array.
Memory Efficiency Consumes more memory, as it creates a new array. More memory-efficient, as it often returns a view without copying.
Performance Can be slower due to copying elements. Can be faster as it avoids copying when possible.
Flexibility Offers more control over memory allocation and copying behavior. Provides a balance between control and memory efficiency.
Order Argument Doesn't have an 'order' argument Has an 'order' argument to specify element arrangement ('C' or 'F').

 

Frequently Asked Questions

When should I use np.flatten()?

Use np.flatten() when you require a fresh one-dimensional array containing all the values from a multi-dimensional array, and memory efficiency is not your main consideration.

When should I use np.ravel()?

Use np.ravel() when you want to convert a multi-dimensional array into a one-dimensional array while aiming for memory efficiency, either by creating a view or, if necessary, a new array.

How do np.flatten() and np.ravel() handle multidimensional arrays?

Both np.flatten() and np.ravel() transform multi-dimensional arrays into one-dimensional arrays. However, np.flatten() creates a new copy of the data in a fresh one-dimensional array, while np.ravel() either provides a memory-efficient view of the existing array's elements or, if needed, creates a new one-dimensional array while maintaining memory efficiency.

Conclusion

The key distinction between the flatten() and ravel() functions in NumPy is that flatten() always creates a new independent copy of the data as a one-dimensional array, while ravel() aims for memory efficiency by either offering a view of the existing array or creating a new one-dimensional array only when necessary.

You can read these articles to learn more.

 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

We wish you Good Luck! 

Happy Learning!

Live masterclass