Home > Software engineering >  How to get every element from a list of list (matrix) using for-loop
How to get every element from a list of list (matrix) using for-loop

Time:06-25

M = [[0,1,0,1],[0,0,1,0]]
    
for i in range(len(M)): 
    print(M[i][i])

How to get the element of an element in a list within a loop in python

I can't remember, it's seems to work with M[i][0] or M[i][1] but I want to do it within a loop

CodePudding user response:

To see all the numbers on separate lines:

for entry in M:
    for i in entry:
        print(i)

CodePudding user response:

Also, you can use indexes to traverse the elements using [:] accessing operator for lists:

M = [[0,1,0,1],[0,0,1,0]]

for i in range(len(M)):
  for j in range(len(M[i])):
    print(M[i][j])

CodePudding user response:

Can be done using list comprehension is required output is list

[j for i in M for j in i ]
  • Related