How to Convert a List to a Matrix in Python

By Michael Carroll

Matrices are not represented by any built-in data type in Python, but may be represented as a nested list, or a list of lists. Create a list and use a "while" loop, the "append" method and list slicing to convert the list to a matrix. This is a good programming exercise, if not a mathematically meaningful one.

Launch the Python command-line interpreter.

Create a simple list with the following command:

list = [1,2,3,4,5,6,7,8,9]

Create an empty variable called "matrix" to store the matrix:

matrix = []

Initiate a "while" loop:

while list != []:

The loop does not execute immediately, and any following commands preceded by a tab character become part of the loop.

Type a tab character, then the following command:

matrix.append(list[:3])

This command slices the first three items from the list and adds them to the matrix.

Entab the next line and type the following command:

list = list[3:]

This command removes the first three items from the list, so that on the next iteration of the loop, the fourth, fifth and sixth items are sliced and added to the matrix, and so on.

Press "Enter" to insert a blank line and execute the loop. Type "matrix" and see that the list's items now form the rows of a 3-by-3 matrix, represented as a nested list.

×