Asked 11 years, 2 months ago
Viewed 2.8m times
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
22.2k16 gold badges86 silver badges127 bronze badges
asked Jul 12, 2011 at 15:54
Masoud AbasianMasoud Abasian
10.2k6 gold badges22 silver badges22 bronze badges
3
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
2,9315 gold badges31 silver badges48 bronze badges
answered Jul 12, 2011 at 15:59
14
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.
answered Jul 12, 2011 at 16:04
senderlesenderle
140k35 gold badges206 silver badges231 bronze badges
6
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]]
answered Jul 12, 2011 at 16:17
Andrew ClarkAndrew Clark
195k33 gold badges264 silver badges297 bronze badges
11
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]]
answered Jul 12, 2011 at 16:00
mripardmripard
2,1882 gold badges13 silver badges11 bronze badges
3
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.
answered May 29, 2014 at 7:23
enobayramenobayram
4,55822 silver badges35 bronze badges
8
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]]
answered Jul 12, 2011 at 16:04
wberrywberry
17.7k8 gold badges51 silver badges82 bronze badges
1
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.
answered Jul 6, 2018 at 21:06
unknownerrorunknownerror
2,0552 gold badges22 silver badges24 bronze badges
0
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
[[], [], []]
answered Dec 4, 2015 at 14:13
FabianFabian
5,3364 gold badges33 silver badges45 bronze badges
0
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 "", line 1, in
IndexError: list index out of range
answered Jul 12, 2011 at 16:00
utdemirutdemir
25.8k10 gold badges61 silver badges81 bronze badges
1
Use:
matrix = [[0]*5 for i in range[5]]
The *5 for the first dimension works because at this level the data is immutable.
answered Aug 5, 2015 at 1:10
innov8innov8
1,9252 gold badges20 silver badges29 bronze badges
1
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.
answered Jun 3, 2018 at 15:32
MichaelMichael
68510 silver badges25 bronze badges
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]
answered Jul 2, 2016 at 11:33
0
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. [//www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays]
answered Dec 7, 2013 at 20:45
khazkhaz
3023 silver badges11 bronze badges
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
answered Mar 28, 2014 at 10:14
user110954user110954
7318 silver badges8 bronze badges
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]]
answered Aug 3, 2019 at 9:42
Meraj al MaksudMeraj al Maksud
1,4522 gold badges22 silver badges35 bronze badges
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]
answered Sep 15, 2017 at 10:54
1
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]
answered Sep 4, 2013 at 19:40
wsanderswsanders
1984 silver badges8 bronze badges
0
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],
...
answered Jan 16, 2017 at 6:38
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.
answered Nov 1, 2015 at 7:48
pterodragonpterodragon
4219 silver badges16 bronze badges
1
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.
answered Jul 14, 2016 at 8:55
alessadnroalessadnro
711 silver badge2 bronze badges
1
l=[[0]*[L] for _ in range[W]]
Will be faster than:
l = [[0 for x in range[L]] for y in range[W]]
answered Nov 18, 2018 at 14:02
Harsh SharmaHarsh Sharma
10.4k2 gold badges16 silver badges27 bronze badges
1
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
answered Feb 5, 2018 at 4:27
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]]
answered Aug 5, 2017 at 11:55
Nagendra NigadeNagendra Nigade
8162 gold badges11 silver badges27 bronze badges
# 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,2593 gold badges35 silver badges44 bronze badges
answered Feb 8, 2014 at 10:24
和風信使和風信使
1351 silver badge2 bronze badges
6
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.
answered Dec 9, 2019 at 12:54
Chandra ShekharChandra Shekhar
5761 gold badge7 silver badges23 bronze badges
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]]
answered Dec 7, 2021 at 20:35
dejanualexdejanualex
3,3316 gold badges22 silver badges33 bronze badges
Try this:
rows = int[input['Enter rows\n']]
my_list = []
for i in range[rows]:
my_list.append[list[map[int, input[].split[]]]]
answered Dec 28, 2018 at 8:45
Ankit SharmaAnkit Sharma
1,4911 gold badge13 silver badges18 bronze badges
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]]
answered Jan 21, 2019 at 17:15
Vlad BezdenVlad Bezden
76k23 gold badges236 silver badges175 bronze badges
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
713k171 gold badges1314 silver badges1433 bronze badges
answered May 24, 2021 at 11:35
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
answered Jun 18 at 11:26
MarioMario
293 bronze badges