Initialize Matrix in Python


In this article, we will learn about how we can initialize matrix using two dimensional list in Python 3.x. Or earlier.

Let’s see the intuitive way to initialize a matrix that only python language offers. Here we take advantage of List comprehension. we initialise the inner list and then extend to multiple rows using the list comprehension.

Example

# input the number of rows
N = 3
# input the number of columns
M = 3
# initializing the matrix
res = [ [ i*j for i in range(N) ] for j in range(M) ]

# printing the matrix on screen row by row in a single line
print("Inline representation:")
[ [ print(res[i][j] ,end =" ") for i in range(N) ] for j in range(M) ]
print("")
# printing in multiple lines
print("Multiline representation")
for i in range(N):
   for j in range(M):
      print(res[i][j] ,end =" ")
   print("")

Output

Inline representation:
0 0 0 0 1 2 0 2 4
Multiline representation
0 0 0
0 1 2
0 2 4

Now let's see the general way which can be implemented in any language. This is the standard way of creating a matrix or multidimensional-array

Example

# input the number of rows
N = 3
# input the number of columns
M = 3
lis=[[0,0,0],[0,0,0],[0,0,0]]
# initializing the matrix
for i in range(N):
   for j in range(M):
      lis[i][j]=i
# multiline representation
for i in range(N):
   for j in range(M):
      print(lis[i][j],end=" ")
   print("")

Output

0 0 0
0 1 2
0 2 4

Conclusion

In this article, we learned how to implement logic gates in Python 3.x. Or earlier. We also learned about two universal gates i.e. NAND and NOR gates.

Updated on: 07-Aug-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements