numpy.ndarray.view() in Python

`numpy.ndarray.view()` helps to get a new view of array with the same data.

Syntax: ndarray.view(dtype=None, type=None)

Parameters:
dtype : Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a.
type : Python type, optional

Returns : ndarray or matrix.

Code #1:

 `# Python program explaining   ` `# numpy.ndarray.view() function  ` ` `  `import` `numpy as geek ` ` `  `a ``=` `geek.arange(``10``, dtype ``=``'int16'``) ` ` `  `print``(``"a is: \n"``, a) ` ` `  `# using view() method ` `v ``=` `a.view(``'int32'``) ` `print``(``"\n After using view() with dtype = 'int32' a is : \n"``, a) ` ` `  `v ``+``=` `1` ` `  `# addition of 1 to each element of v ` `print``(``"\n After using view() with dtype = 'int32' and adding 1 a is : \n"``, a) `

Output:

```a is:
[0 1 2 3 4 5 6 7 8 9]

After using view() with dtype = 'int32' a is :
[0 1 2 3 4 5 6 7 8 9]

After using view() with dtype = 'int32' and adding 1 a is :
[1 1 3 3 5 5 7 7 9 9]
```

Code #2:

 `# Python program explaining   ` `# numpy.ndarray.view() function  ` ` `  `import` `numpy as geek ` ` `  `a ``=` `geek.arange(``10``, dtype ``=``'int16'``) ` `print``(``"a is:"``, a) ` ` `  `# Using view() method ` `v ``=` `a.view(``'int16'``) ` `print``(``"\n After using view() with dtype = 'int16' a is :\n"``, a) ` ` `  `v ``+``=` `1` `# addition of 1 to each element of v ` `print``(``"\n After using view() with dtype = 'int16' and adding 1 a is : \n"``, a) `

Output:

```a is: [0 1 2 3 4 5 6 7 8 9]

After using view() with dtype = 'int16' a is :
[0 1 2 3 4 5 6 7 8 9]

After using view() with dtype = 'int16' and adding 1 a is :
[ 1  2  3  4  5  6  7  8  9 10]
```

Code #3:

 `# Python program explaining   ` `# numpy.ndarray.view() function  ` ` `  `import` `numpy as geek ` ` `  `a ``=` `geek.arange(``10``, dtype ``=``'int16'``) ` `print``(``"a is: \n"``, a) ` ` `  `v ``=` `a.view(``'int8'``) ` `print``(``"\n After using view() with dtype = 'int8' a is : \n"``, a) ` ` `  `v ``+``=` `1` `# addition of 1 to each element of v ` `print``(``"\n Ater using view() with dtype = 'int8' and adding 1 a is : \n"``, a) `

Output:

```a is:
[0 1 2 3 4 5 6 7 8 9]

After using view() with dtype = 'int8' a is :
[0 1 2 3 4 5 6 7 8 9]

Ater using view() with dtype = 'int8' and adding 1 a is :
[257 258 259 260 261 262 263 264 265 266]
```

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.