# 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.

#### Step 1

Launch the Python command-line interpreter.

#### Step 2

Create a simple list with the following command: list = [1,2,3,4,5,6,7,8,9]

#### Step 3

Create an empty variable called "matrix" to store the matrix: matrix = []

#### Step 4

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.

#### Step 5

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.

#### Step 6

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.