Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

import numpy as np

y = np.array(((1,2,3),(4,5,6),(7,8,9)))

OUTPUT:

print(y.flatten())

[1 2 3 4 5 6 7 8 9]

print(y.ravel())

[1 2 3 4 5 6 7 8 9]

Both functions return the same list. Then what is the need for two different functions performing the same job?

1 Answer

0 votes
by (106k points)

The difference between flatten and ravel functions in numpy is as follows:-

  • The flatten method always returns a copy.

  • Whereas the ravel method returns a view of the original array whenever possible. When you print the output this will not be visible, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen. The ravel will often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.

  • If you use the reshape((-1,)) it gets a view whenever the strides of the array allow it even if that means you don't always get a contiguous array.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...