Matrices in Python

Python is known for its neatness and clean data readability and handling feature. There are various techniques for handling data in Python such as using Dictionaries, Tuples, Matrices, etc. In this tutorial, you will learn about the matrices and its functionalities.

What is Matrix in Python?

These are 2D (two dimensional) data structure. In live projects and real data simulation, you have to keep the data in a sequential or tabular format. Let suppose you want to store data of three employees of three different departments. So in tabular format, it will look something like:

Employee IDEmployee NameEmployee Dept
1001ARayTechnical Head
2004BKarlosManager
3100AAlexLead Developer

In Python, these tables are termed as two-dimensional arrays, which are also called matrices. Python gives us the facility to represent these data in the form of lists.

Example:
val = [['1001A','Ray', 'Technical Head'], ['2004B', 'Karlos' , 'Manager'], ['3100A', 'Alex' , 'Lead Developer']]

In the above code snippet, val represents a 3 X 3 matrix where there are three rows and three columns.

Create a Matrix in Python

Python allows developers to implement matrices using the nested list. Lists can be created if you place all items or elements starting with '[' and ending with ']' (square brackets) and separate each element by a comma.

val = [['Dave',101,90,95],

['Alex',102,85,100],

['Ray',103,90,95]]

Dynamically Create Matrices in Python

It is possible to create a n x m matrix by listing a set of elements (let say n) and then making each of the elements linked to another 1D list of m elements. Here is a code snippet for this:

n = 3
m = 3
val = [0] * n
for x in range (n):
    val[x] = [0] * m
print(val)

Program output will be:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Accessing Elements of Matrices

There are different methods of obtaining elements of a matrix in Python.

i) List Index: For accessing elements of the matrix, you have to use square brackets after the variable name with the row and column number, like this val[row_no][col_no]

val = [['Dave',101,90,95], ['Alex',102,85,100], ['Ray',103,90,95]]

print(val[2])

print(val[0][1])
Output:
['Ray',103,90,95]

101

ii) Negative Indexing: Python also provides the feature for indexing with negative values in its square brackets for accessing values sequentially. In negative indexing, -1 refers to the last element of the matrix, -2 as the 2nd last and continues.

val = [['Dave',101,90,95], ['Alex',102,85,100], ['Ray',103,90,95]]

print(val[-2])

print(val[-1][-2])
Output:
['Alex',102,85,100]

90

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.