✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Create a Two Dimensional List in Python

Sep 13, 2020 2 min read

The need to create two dimensional (2D) lists and arrays is quite common in any programming languages. I happen to be working in Python when I most recently came across this question.

Suppose I wanted to create a 2D list, or matrix, like this:

1, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 1, 1, 1, 1

In memory, a 2D list looks like a list of lists.

[
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
]

We can create a list just using [], but we can’t use [][] to create a 2D list.

The following ways, both of which use list comprehension, have worked for me.

Method 1

matrix = [[1 for i in range(5)] for j in range(5)]

In this method, we’re first creating a list [1, 1, 1, 1, 1] in left for loop.

We’re then creating the list of lists, or 2D list, using the right loop.

Method 2

matrix = [x[:] for x in [[1] * 5] * 5]

On the right side, [[1] * 5] * 5] creates a 2D list that looks normal.

[
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
]

However, it actually creates a list of the exact same list object 5 times. This means that modifying the first element in one row will change the first element in every row of that list.

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

To circumvent this issue, we can make shallow copies of each row using x[:], and store it into a new list object.

Do note that this method is faster than Method 1.