How to Create a Matrix in Python Without NumPy

How to Create a Matrix in Python Without NumPy | Here, we will discuss how to create a matrix in python without NumPy. Matrix is a rectangular table arranged in the form of rows and columns, in the programming world we implement matrix by using arrays by classifying it as 1D and 2D arrays. In this section, there are some examples to create a matrix in python without using NumPy.

How to Create a Matrix in Python Without NumPy

The matrix can be created without using NumPy, the below code creates a 2D matrix using the nested list. A nested list is a list within a list.

m = [[9, 5, 7], [1, 3, 6], [5, 0, 8]]
for i in m:
   print(i)

Output:

[9, 5, 7]
[1, 3, 6]
[5, 0, 8]

In the example shown we have declared variable m as a nested list and then used a for loop to print all the elements, without a for loop the elements have been printed in a single line.

Python Program to Create a Matrix Using join() Function

This python program also performs the same task but in different ways. In this program, we use the join function to create a matrix in python. The join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.

m = ([1, 2, 3], [7, 1, 5], [0, 9, 3])
for i in m:
   print("". join(str(i)))

Output:

[1, 2, 3]
[7, 1, 5]
[0, 9, 3]

The above shown both examples give the same output but the difference is join() function joins the elements of a row into a single string before printing it.

Make a Matrix in Python Without Using NumPy

Step 1: We have first a single list.
Step 2: Then we iterate by for loop to print it twice using a range within the list it will change into nested list acting as a matrix

m = [[1, 2, 3] for i in range(3)]
for i in m:
   print("".join(str(i)))

Output:-

[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

In the above output, we have printed the list twice by giving the range parameter as 3.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *