# numpy.diag_indices() in Python

numpy.diag_indices(n, n_dim = 2) : Returns indices in order to access the elements of main diagonal of a array with minimum dimension = 2. Returns indices in the form of tuple.
to access the main diagonal of an array.

Parameters :

```n : size of array, for which indices of diag elements are required along each dimension
n_dim  : [int, optional]number of dimensions.
```

Return :

```Indices(as tuples) to access diagonal elements.
```

Code 1 :

 `# Python Program illustrating ` `# working of diag_indices() ` ` `  `import` `numpy as geek  ` ` `  `# Creates a 5 X 5 array and returns indices of ` `# main diagonal elements ` `d ``=` `geek.diag_indices(``5``) ` `print``(``"Indices of diagnol elements as tuple : "``) ` `print``(d, ``"\n"``) ` ` `  `array ``=` `geek.arange(``16``).reshape(``4``,``4``) ` `print``(``"Initial array : \n"``, array) ` ` `  `# Here we can manipulate diagonal elements ` `# by accessing the diagonal elements ` `d ``=` `geek.diag_indices(``4``) ` `array[d] ``=` `25` `print``(``"\n New array : \n"``, array) `

Output :

```Indices of diagnol elements as tuple :
(array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))

Initial array :
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]

New array :
[[25  1  2  3]
[ 4 25  6  7]
[ 8  9 25 11]
[12 13 14 25]]
```

Code 2 : Manipulating 2D array

 `# Python Program illustrating ` `# working of diag_indices() ` ` `  `import` `numpy as geek  ` ` `  `# Manipulating a 2D array  ` `d ``=` `geek.diag_indices(``3``, ``2``) ` ` `  `array ``=` `geek.arange(``12``).reshape(``4``, ``3``) ` ` `  `array[d] ``=` `111` `print``(``"Manipulated array : \n"``, array) `

Output :

```Manipulated array :
[[111   1   2]
[  3 111   5]
[  6   7 111]
[  9  10  11]]
```

Code 3 : Manipulating 3D array

 `# Python Program illustrating ` `# working of diag_indices() ` ` `  `import` `numpy as geek  ` ` `  `# Setting diagonal indices ` `d ``=` `geek.diag_indices(``1``, ``2``) ` `print``(``"Diag indices : \n"``, d) ` ` `  `# Creating a 3D array with all ones ` `array ``=` `geek.ones((``2``, ``2``, ``2``), dtype``=``geek.``int``) ` `print``(``"Initial array : \n"``, array) ` ` `  `# Manipulating a 3D array  ` `array[d] ``=` `0` `print``(``"New array : \n"``, array) `

Output :

```Diag indices :
(array(), array())
Initial array :
[[[1 1]
[1 1]]

[[1 1]
[1 1]]]
New array :
[[[0 0]
[1 1]]

[[1 1]
[1 1]]]
```

Note :
These codes won’t run on online-ID. Please run them on your systems to explore the working.

This article is contributed by Mohit Gupta_OMG 😀. 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.