891

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

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Masoud Abasian
  • 10,549
  • 6
  • 23
  • 22
  • 18
    One does not *define arrays*, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python *variables* are untyped, but *values* are strongly typed. – SingleNegationElimination Jul 12 '11 at 16:05
  • 2
    I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here... – Dirk Reichel Jun 05 '18 at 19:48
  • 4
    See also the Python3 FAQ on [How do I create a multidimensional list?](https://docs.python.org/3/faq/programming.html#faq-multidimensional-list) – Kevin W Matthews Aug 17 '19 at 21:08

30 Answers30

1230

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)] 

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

Saeed
  • 3,294
  • 5
  • 35
  • 52
Manny D
  • 20,310
  • 2
  • 29
  • 31
  • 250
    [[0 for x in range(cols_count)] for x in range(rows_count)] – songhir Nov 27 '14 at 02:48
  • 3
    Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects. – Dave Nov 25 '15 at 07:29
  • 4
    @dave If you dont need it zero-filled, can use `range` to create the internal lists directly: ``[range(5) for x in range(5)]`` – alanjds Dec 09 '15 at 22:08
  • 2
    @alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction. – Dave Dec 10 '15 at 16:00
  • 1
    w, h = 8, 5. should be corrected to w, h = 8, 5; That trailing decimal does some odd things with the variable definition for h – JJFord3 Nov 15 '16 at 18:18
  • 2
    Wouldn't following be more concise?: ```[[0] * w] * h``` – Aaron S Apr 25 '17 at 07:43
  • 22
    @6packkid the `[0] * w` part is nice, but `[[0] * w] * h]` will produce unexpected behavior. Try `mat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]])` and `mat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]])`. – senderle Jul 19 '17 at 15:45
  • 1
    If the number of sublists is h, shouldn't the first index be y? As in Matrix[y][x]. I think you meant Matrix = [[0 for y in range(h)] for x in range(w)] in which case you can use Matrix[x][y]. – Zuzu Corneliu Jun 30 '18 at 12:58
  • You flipped your width and height on the matrix. `Matrix = [[0 for x in range(w)] for y in range(h)]` is accessed by `Matrix[y][x]` not `Matrix[x][y]`. Just try running `Matrix[7][2]` and see what you get. – rovyko Aug 25 '18 at 04:52
  • 4
    @6packkid this uses the *same* array h times (and hence changing one impacts all rows). Try for example `test = [[0]*3]*5; test[1][1]=7; print(test)` – Marc Van Daele Oct 15 '18 at 09:18
  • You can also do this: `array = [[]]` – Dwa Dec 04 '19 at 00:57
  • Matrix = [[0 for col in range(w)] for row in range(h)] – jack Aug 29 '20 at 19:28
  • the edit que is full, so have left as a comment.. please remove the semi-colon from the end of this line `w, h = 8, 5;` – D.L Apr 29 '21 at 08:35
473

If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.

senderle
  • 145,869
  • 36
  • 209
  • 233
  • 97
    Whenever you want matrices, you want to use numpy. This answer should be first. – Pat B Jul 12 '11 at 16:14
  • 4
    The fact that the question uses the English word "matrix" doesn't mean that they should use `np.matrix` to represent it. The proper way to represent a matrix in numpy is with an `array`. – user2357112 Nov 05 '17 at 20:39
  • @user2357112, And as you can see, *most* of the examples listed above output `array`s instead of matrices. While it isn't always encouraged, there are legitimate reasons for using `matrix` -- context matters. – senderle Nov 05 '17 at 21:23
  • 1
    @senderle, Can you expand on reasons to use `matrix`? Since `@` operator was introduced, there seems to be one less reason since this post was written. – jpp Jul 14 '18 at 10:29
  • 2
    @jpp, as the post previously said, people coming from matlab might find it useful. But the `numpy` docs now indicate that the class may be deprecated and [removed](https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html) in the future, so I've taken it out of the answer. – senderle Feb 01 '20 at 16:37
  • numpy is optimal if all elements of the matrix are of the same type. if elements are not the same type (ie. int, float, bool, str), then need regular python matrix. – D.L Apr 29 '21 at 08:41
  • May I ask the difference between ` numpy.zeros((5, 5))` and ` numpy.zeros([5, 5])` ? They put out the same result but I wonder if there is still difference. – Wei Shan Lee Jan 24 '23 at 13:14
397

Here is a shorter notation for initializing a list of lists:

matrix = [[0]*5 for i in range(5)]

Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:

>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 11
    Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of `[0]*5`? – mike622867 Mar 22 '15 at 23:00
  • 22
    The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.) – dreua Jan 26 '18 at 10:49
  • 11
    more pythonic: `[[0]*5 for _ in range(5)]` with anonymous loop counter you're not using – Jean-François Fabre Nov 11 '18 at 20:38
  • 1
    Nice that you point out the problem of shallow copy in the second example. – whatacold Dec 08 '19 at 02:51
  • thanks @dreua, I was really confused how `[0]*5` works just fine. Now I understand why `[{0}]*8` would be a bad idea also. – kuku Mar 07 '20 at 18:50
  • @kuku what is the meaning of [{0}] in python? – apadana May 23 '20 at 22:33
  • @Jean-FrançoisFabre this looks nicer to the eye, but note that `_` is not actually an anonymous binder, it is a valid variable name, e.g. `[_ for _ in range(5)]` produces the list `[0, 1, 2, 3, 4]`. – Maëlan Nov 22 '20 at 16:25
  • this is anonymous by intent. it tells you that you should not use the identifier. – Jean-François Fabre Nov 22 '20 at 16:37
  • 2
    The throw-away note "Unfortunately shortening this to something like 5*[5*[0]] doesn't really work" should be much higher up this page as its not obvious to many poeple – jcansell Jan 07 '21 at 15:03
  • 2
    Yes, and the [document](https://docs.python.org/3/faq/programming.html#faq-multidimensional-list) of python3 also mentions it. – Brainor Jul 05 '21 at 08:21
  • 1
    @jcansell And it will bite you silently when you think your script writes one value, but instead it assigns the whole column. I added this to my list of gotchas. – SurpriseDog Apr 14 '22 at 00:50
143

If you want to create an empty matrix, the correct syntax is

matrix = [[]]

And if you want to generate a matrix of size 5 filled with 0,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]
mripard
  • 2,298
  • 2
  • 14
  • 11
91

If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:

Matrix = {}

Then you can do:

Matrix[1,2] = 15
print Matrix[1,2]

This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.

As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.

Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
enobayram
  • 4,650
  • 23
  • 36
  • 2
    Then you can also do `import collections; Matrix = collections.defaultdict(float)`, to substitute zeros for uninitialized elements. – Sergey Orshanskiy Oct 22 '15 at 16:17
  • 2
    Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice. – DoOrDoNot Nov 16 '15 at 12:25
  • @Vatsal https://wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time. – enobayram Nov 16 '15 at 13:38
  • Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity. – DoOrDoNot Nov 16 '15 at 14:28
  • 1
    @enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments – DoOrDoNot Nov 17 '15 at 04:10
  • @Vatsal it's not O(n) but O(k) where k is the size of the tuple and since in this case it is fixed it is equivalent to O(1). – Sandeep Datta Jul 18 '19 at 20:44
49

In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:

matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)

Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":

from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
wberry
  • 18,519
  • 8
  • 53
  • 85
  • 6
    `extend` would also be helpful in the first case: If you start with `m = [[]]`, then you could add to the inner list (extend a row) with `m[0].extend([1,2])`, and add to the outer list (append a new row) with `m.append([3,4])`, those operations would leave you with `[[1, 2], [3, 4]]`. – askewchan Oct 09 '13 at 16:59
32

Here's the code for a beginner whose coming from C, CPP and Java background

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.)

miken32
  • 42,008
  • 16
  • 111
  • 154
unknownerror
  • 2,235
  • 2
  • 25
  • 26
25

The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.

l =  [[] for _ in range(3)]

results in

[[], [], []]
Fabian
  • 5,476
  • 4
  • 35
  • 46
25

You should make a list of lists, and the best way is to use nested comprehensions:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
utdemir
  • 26,532
  • 10
  • 62
  • 81
  • Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]' – Aniruddha Kalburgi Sep 30 '18 at 01:45
17

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.

Michael
  • 713
  • 10
  • 27
15

Use:

matrix = [[0]*5 for i in range(5)]

The *5 for the first dimension works because at this level the data is immutable.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
innov8
  • 2,093
  • 2
  • 24
  • 31
14

A rewrite for easy reading:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_count = 5

# create
#     creation looks reverse
#     create an array of "cols_count" cols, for each of the "rows_count" rows
#        all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]

# index is from 0 to 4
#     for both rows & cols
#     since 5 rows, 5 cols

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
13

To declare a matrix of zeros (ones):

numpy.zeros((x, y))

e.g.

>>> numpy.zeros((3, 5))
    array([[ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

or numpy.ones((x, y)) e.g.

>>> np.ones((3, 5))
array([[ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.]])

Even three dimensions are possible. (http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)

khaz
  • 369
  • 3
  • 12
12

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]]
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
11

I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:

 # Creates a 2 x 5 matrix
 Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

so that

Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user110954
  • 751
  • 8
  • 9
10

Using NumPy you can initialize empty matrix like this:

import numpy as np
mm = np.matrix([])

And later append data like this:

mm = np.append(mm, [[1,2]], axis=1)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Namrata Tolani
  • 823
  • 9
  • 12
8

I read in comma separated files like this:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

The list "data" is then a list of lists with index data[row][col]

wsanders
  • 300
  • 5
  • 9
7

Use:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pterodragon
  • 429
  • 8
  • 16
7

If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:

import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()

The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alessadnro
  • 71
  • 1
  • 2
7

That's what dictionary is made for!

matrix = {}

You can define keys and values in two ways:

matrix[0,0] = value

or

matrix = { (0,0)  : value }

Result:

   [ value,  value,  value,  value,  value],
   [ value,  value,  value,  value,  value],
   ...
Community
  • 1
  • 1
6
l=[[0]*(L) for _ in range(W)]

Will be faster than:

l = [[0 for x in range(L)] for y in range(W)] 
Harsh Sharma
  • 10,942
  • 2
  • 18
  • 29
  • 3
    Duplicate answer of one already answered below. Also `[[0]*(L) for i in range(W)]` should be `[[0]*(L) for _ in range(W)]` since `i` isn't used anywhere – Ayush Vatsyayan Jan 08 '19 at 03:39
5

If you don't have size information before start then create two one-dimensional lists.

list 1: To store rows
list 2: Actual two-dimensional matrix

Store the entire row in the 1st list. Once done, append list 1 into list 2:

from random import randint

coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
    randomx=randint(0,1000)
    randomy=randint(0,1000)
    temp=[]
    temp.append(randomx)
    temp.append(randomy)
    coordinates.append(temp)

print coordinates

Output:

Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
Nagendra Nigade
  • 866
  • 2
  • 12
  • 28
4

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

Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
2
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5

Be careful about this short expression, see full explanation down in @F.J's answer

gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
和風信使
  • 133
  • 1
  • 2
  • 21
    Be careful in this way, because `Matrix[0], Matrix[1], ..., Matrix[4]` all point to the same array, so after `Matrix[0][0] = 3`, you would expect `Matrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3`. – gongzhitaao Apr 03 '14 at 19:38
  • 1
    Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do. – Adrian Nov 20 '14 at 02:18
  • 7
    You should remove this answer, since it's not correct answer. Beginners might be confused. – cxxl Nov 25 '16 at 20:58
  • 2
    What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers). – Peter Mortensen Nov 12 '17 at 13:18
  • @PeterMortensen I think it has been deleted by now. Better look at answer (above, by Andrew Clark) at: https://stackoverflow.com/a/6667529/3693431. – jiten Dec 29 '20 at 09:02
  • As mentioned above this is incorrect and can lead to subtle hard to find bugs – kohlerm Dec 07 '21 at 13:40
2

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.

Chandra Shekhar
  • 598
  • 1
  • 7
  • 25
2

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))
dejanualex
  • 3,872
  • 6
  • 22
  • 37
1

Try this:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))
Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21
1

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]]
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
1

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sanjay Rai
  • 27
  • 3
-2

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
Mario
  • 35
  • 3
  • 2
    I tried this and it caused each outer array element to point to the same inner array, i.e. when I changed [1][3], then [2][3] was changed in the same way. – Alexander Stumpf Dec 08 '22 at 09:09