How to Create a Matrix in Python Using For Loop

How to Create a Matrix in Python Using For Loop | Here, we will discuss how to create a matrix in python using for loop. 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 using the For Loop.

How to Create a Matrix in Python Using For Loop

In this program, matrices can be created using the for loop and join function. 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.

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, 9, 7, 4] for i in range(4)]
for i in m:
   print("".join(str(i)))

Output:-

[1, 9, 7, 4]
[1, 9, 7, 4]
[1, 9, 7, 4]
[1, 9, 7, 4]

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

How to Make a Matrix in Python Using For Loop

The below code creates a 2D matrix using the nested list. A nested list is a list within a list.

m = [[1, 3, 5], [1, 5, 2]]
for i in m:
   print(i)

Output:-

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

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 For Loop

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.

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

Output:-

[3, 5, 9]
[9, 0, 4]

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.

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 *