15,669,524 members
See more:
Hi, I create matrix "adjacency_matrix" with following code:

Python
```n = int(input()) # Initialize matrix

# For user input

for i in range(n):

a =[]

for j in range(n):

a.append(int(input()))

I want to save indices of non zero elements of above matrix.

for example n = 3;

Python
```adjacency_matrix =

2 3 0

0 0 1

1 5 0```

I want to save rows of non zero element in "li_r":

Python
`li_r = [0 0 1 2 2]`

I want to save columns of non zero element in "li_c":

Python
`li_c = [0 1 2 0 1]`

My Question is: Is this code is true?

Python
```for i in range(n):

li_r = [];

li_c = []

for j in range(n):

li_r.append(i-1)

li_c.append(j-1)```

What I have tried:

I write that code, by it's not work.
Posted
Updated 15-Jun-22 20:30pm

## Solution 1

Try the following code
Python
```n=3
adjacency_matrix =[ [2, 3, 0] , [0, 0, 1] , [1, 5, 0] ]

li_r = []
li_c = []
for i in range(n):
for j in range(n):
li_r.append(i)
li_c.append(j)

print(li_r)
print(li_c)```

You may also use the more concise, but less efficient
Python
```n=3
adjacency_matrix =[ [2, 3, 0] , [0, 0, 1] , [1, 5, 0] ]

li_r = [r for r in range(n) for c in range(n) if adjacency_matrix[r][c] != 0]
li_c = [c for r in range(n) for c in range(n) if adjacency_matrix[r][c] != 0]

print(li_r)
print(li_c)```

v2