This post will discuss how to construct and initialize two-dimensional lists in Python.

You must never initialize a two-dimensional list using the expression [[val]*c]*r. This might result in reference errors since the resultant list contains the same list instance repeated r times. The following example demonstrates this behavior:

Download  Run Code

 
This post provides an overview of some of the available alternatives to create and initialize two-dimensional lists in Python correctly.

1. Using List Comprehension

A simple yet elegant solution to initialize two-dimensional lists in Python is using list comprehensions:

Download  Run Code

 
This can be further shortened as follows:

Download  Run Code

2. Using NumPy

Alternatively, you can use NumPy to declare and initialize two-dimensional lists in Python. Here’s what the code would look like:

 
With NumPy 1.8, you can use the np.full() function, which declares and initialize the matrix in a single step.

 
If you need a matrix with the values initialized with all zeros or ones, you can use the np.zeros() and np.ones() function, respectively:

 
Another plausible way to construct a two-dimensional list with NumPy is to create a single-dimensional list filled with desired values and then reshape it to two-dimensions using the np.reshape() function.

That’s all about declaring and initializing two-dimensional lists in Python.