How to define a two-dimensional array in Python

701    Asked by RutujaMishra in Python , Asked on Apr 10, 2021

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 not working:

Matrix = [5][5]

Error:

Traceback ... 

IndexError: list index out of range

How python define 2d array ? What’s wrong please suggest.

Answered by Rutuja Mishra

In Python for defining 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 python define 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))



Your Answer

Interviews

Parent Categories