I want to define a two-dimensional array without an initialized length like this:
Matrix = [][]
But this gives an error:
IndexError: list index out of range
I want to define a two-dimensional array without an initialized length like this:
Matrix = [][]
But this gives an error:
IndexError: list index out of range
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using two for loops in a list comprehension.
You can create an empty two dimensional list by nesting two or more square bracing or third bracket ([], separated by comma) with a square bracing, just like below:
Matrix = [[], []]
Now suppose you want to append 1 to Matrix[0][0] then you type:
Matrix[0].append(1)
Now, type Matrix and hit Enter. The output will be:
[[1], []]
If you entered the following statement instead
Matrix[1].append(1)
then the Matrix would be
[[], [1]]
l=[[0]*(L) for _ in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict: you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
Here is the code snippet for creating a matrix in python:
# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))
# initialize the list
l=[[0]*cols for i in range(rows)]
# fill some random values in it
for i in range(0,rows):
for j in range(0,cols):
l[i][j] = i+j
# print the list
for i in range(0,rows):
print()
for j in range(0,cols):
print(l[i][j],end=" ")
Please suggest if I have missed something.
Usually, the go-to module is NumPy:
import numpy as np
# Generate a random matrix of floats
np.random.rand(cols,rows)
# Generate a random matrix of integers
np.random.randint(1, 10, size=(cols,rows))
Try this:
rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
my_list.append(list(map(int, input().split())))
In case if you need a matrix with predefined numbers you can use the following code:
def matrix(rows, cols, start=0):
return [[c + start + r * cols for c in range(cols)] for r in range(rows)]
assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]
User Define function to input Matrix and print
def inmatrix(m,n):
#Start function and pass row and column as parameter
a=[] #create a blank matrix
for i in range(m): #Row input
b=[]#blank list
for j in range(n): # column input
elm=int(input("Enter number in Pocket ["+str(i)+"]["+str(j)+"] ")) #Show Row And column number
b.append(elm) #add value to b list
a.append(b)# Add list to matrix
return a #return Matrix
def Matrix(a): #function for print Matrix
for i in range(len(a)): #row
for j in range(len(a[0])): #column
print(a[i][j],end=" ") #print value with space
print()#print a line After a row print
m=int(input("Enter number of row")) #input row
n=int(input("Enter number of column"))
a=inmatrix(m,n) #call input matrix function
print("Matrix is ... ")
Matrix(a) #print matrix function
If you want to create a 2d matrix which dimension is defined by two variables and initialise it with a default value for all its elements. You can use this simple syntax
n_rows=3
n_cols=4
aux_matrix= [[1]*n_cols]*n_rows