+ 1

How to convert a list of list to a matrix in python?

eg: input - [[1, 2, 3], [4, 5, 6]] output - 1 2 3 4 5 6

23rd Feb 2019, 8:42 PM
Abhilash Cs
Abhilash Cs - avatar
3 Answers
+ 4
In the example you gave, the input is already a matrix. It may not look like one, but that's how they are used in coding (lists inside lists). This is how they work: The first list inside the whole list ([1,2,3]) is the first row. The other list is the other row. This is very useful because to access an element you do variable[i][j], where i and j are the row and the column, counting from 0.
23rd Feb 2019, 9:32 PM
Zokalyx
Zokalyx - avatar
+ 2
To print the inner lists in separate rows, you can do this: matrix = [[1,2,3],[4,5,6],[7,8,9]] print(*matrix, sep='\n') This is unpacking the first level of the list and puts an endline between each sublist.
24th Feb 2019, 7:37 AM
Tibor Santa
Tibor Santa - avatar
+ 1
To get a clean output for row in matrix: print(*row) The for loop iterates over the matrix list and the asterix unpacks each row list in the print function. As the print function is called for each row it automatically provides a new line.
24th Feb 2019, 2:19 PM
Mike Buttery
Mike Buttery - avatar