Post

PythonPython

christina joce

Posted on 27th April 2024|25 views

0
votes

List To Matrix Python

How to convert a list into a matrix in python?

Answers
P
chris bons

Posted on 27th April 2024

Matrices are not described by a built-in data type within Python but may be described as a nested list, or else a list of lists. Generate any list and utilize a "while" loop, that "append" method also list slicing to turn the list into a matrix. Here is a great programming exercise, if not any mathematically significant one.

Step1:

Launch a python, command-line interpreter.

Step2:

Build a very simple list with the command like list = [1,2,3,4,5,6,7,8,9]

Step3:

Build an empty variable like matrix: matrix = []

Step4:

Start a while loop: while list! = []: this loop does not execute immediately and the commands preceding by any tab character will become part of that loop.

Step5:

Type one tab character, later the following command: matrix.append(list[:3]) The command slices that first three items of the list and appends them over that matrix. 

Step6:

Enter that next line also type this following command: list = list[3:] The command extracts that first three items of the list so that upon the next iteration from the loop, the fourth, fifth and sixth items are sliced also attached to the matrix, etc.

Press "Enter" to include a blank line also execute that loop. Type "matrix" then see that the list's items then form the rows of a 3-by-3 matrix, designated as a nested list.

 

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos