How to Convert a List to a Matrix in Python

104 8
    • 1). Launch the Python command-line interpreter.

    • 2). Create a simple list with the following command:

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

    • 3). Create an empty variable called "matrix" to store the matrix:

      matrix = []

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

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

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

    • 7). 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.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.