Sitemap

Matrix in Python

3 min readJun 6, 2022

--

Formation of matrix of any size using python programming

One of the important built-in data types in Python programming language is list . Lists are used to store multiple elements of any type in a single variable. Unlike strings in python, lists are mutable.

Examples

  1. x = []
  2. y = [5, ‘physics’, ‘91.4’ , [‘history’ , 89]]
  3. z = [[4, 9, 7], [2, 4, 8]]

First example represents an empty list. In lists, indexing starts from zero. Therefore in the second example y[1] refers to the second element in the list i.e. ‘physics’ . The third example represents a 2 x 3 matrix which looks like:

Here z[0] refers to the first element [4, 9, 7] which itself is a list and it represents the first row of the matrix. Whereas z[1] refers to another list element [2, 4, 8] the second row of the matrix. Also z[1][2] refers to the last element 8 which is in the second row and second column.

How to print a 3 x 3 matrix and its square from the given list

Consider that the given list is [[7,3,5], [3,2,6], [7,9,4]]

Get Chaitanya Bhat’s stories in your inbox

Join Medium for free to get updates from this writer.

Solution:

Press enter or click to view image in full size

Output:

The above problem has a drawback. i.e. the user need to enter the elements of the list in the proper (matrix) form and if the user wants to print different size matrix with different elements each time when he/she executes the code, then that is not possible with the above code. So the problem must be generalized.

How to print a square matrix of any given size

Solution:

Press enter or click to view image in full size

Output 1:

Output 2:

Here user can enter any preferred size of the square matrix and its elements.

By understanding the concept of matrix in python, one is able to solve the problem like ‘Showing the possible moves of a horse in a chess board by entering the initial position of the horse’.

Thank you for reading and happy coding.

--

--