How to make a python matrix from the list

Make a matrix out of a list in Python w/ an example: Use list comprehension to quickly create 2D array from a given list.

Creating a Python Matrix from a List

A Python matrix is a two-dimensional array of numbers. It can be created from a list of lists, where each sub-list represents a row of the matrix. In Python, a matrix can be created using the numpy library. The numpy library provides a function called 'array' for creating a matrix from a list. The syntax for using this function is given below:

matrix = numpy.array(list)

Where 'list' is the list of lists from which the matrix is to be created.

For example, consider the following list of lists:

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

The following code can be used to create a matrix from this list:

import numpy

matrix = numpy.array(list)

print(matrix)

The output of this code will be:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

As can be seen from the output, the matrix created from the list of lists is a two-dimensional array of numbers.

In summary, creating a Python matrix from a list is a simple task that can be accomplished using the numpy library. The 'array' function provided by the numpy library can be used to create a matrix from a list of lists.

Answers (0)