2-D List

What is a 2-D List?

In Python, a two-dimensional (2-D) list, also known as a list of lists or a matrix, is a list where each item is itself a list. The sublists are the rows of the matrix, and the items within these sublists form the columns.

Declaring a 2-D List

To declare a 2-D list, you simply nest one set of bracketed items in another.

Here’s a simple example:

1twod_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this example, there are three sublists, each containing three items. The outer list holds the sublists.

Accessing Elements in a 2-D list

In a 2-D list, the first index is for the sublist, the second one is for an item within the sublist.

Here’s how to access the first item (1) from twod_list:

1print(twod_list[0][0])  # Output: 1

Common Usage of 2-D Lists

Two-dimensional lists are frequently used in Python when dealing with grids of values or tables of data. They are especially popular in anguages and libraries or packages for scientific computing and data science, like numpy and pandas.

2-D List Comprehension

You can use list comprehension in 2-D lists. This is a unique Python feature that enables creation, manipulation, and modification of lists in a single, readable, and neat line of code.

Consider the following example where we create a matrix with each cell being the sum of its row and column indices:

1matrix = [[i + j for j in range(5)] for i in range(5)]
2print(matrix)
3# Output: 
4# [[0, 1, 2, 3, 4], 
5#  [1, 2, 3, 4, 5], 
6#  [2, 3, 4, 5, 6], 
7#  [3, 4, 5, 6, 7], 
8#  [4, 5, 6, 7, 8]]

Remember

Be aware that the inner comprehension runs as the nested, ‘inner’ loop and the outer comprehension serves as the container ‘outer’ loop.

With this powerful Python feature, you can manipulate two-dimensional data structures fully, from a computer science perspective, and also perform matrix computation in a simple and effective way from a mathematical perspective.