Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I want to define a two-dimensional array without an initialized length like this:

Matrix = [][]

but it does not work...

I've tried the code below, but it is wrong too:

Matrix = [5][5]


Traceback ... 

IndexError: list index out of range

What is my mistake?

1 Answer

0 votes
by (106k points)
edited by

In Python for constructing 2D-array, you can use list-comprehension as it is the best way to construct a 2D-array. Actually in Python array is nothing but a set of list values.

# Here we are creating a list containing 5 lists, each of the 8 items, all set to 0.

a, b = 8, 5;

Matrix = [[0 for x in range(a)] for y in range(b)]

As our matrix is created, so now we can add items to it by following way:

Matrix[0][0] = 1 

print Matrix[0][0] #it will print 1

Another way you can get a 2D-array by using numpy. Matrix operations in numpy most often used as 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))


To know more about this you can have a look at the following video tutorial:-

If you are looking for upskilling yourself in python you can join our Python Training and learn from the industry expert.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
asked Dec 30, 2020 in Python by ashely (50.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers


108k users

Browse Categories