JS Problems geeksforgeeks Exercises and Solutions for Beginners

How to Create a Two Dimensional List in Python [All Method]️

The step-by-step guide on this page will show you How to Create a Two Dimensional List in Python. By following this guide, you will be able to deal with these sorts of difficulties.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Create a Two Dimensional List in Python. Question: What are the reasons for this code mistake and how can it be fixed? Answer: You can find a solution by following the advice in this blog.

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.


Revise the code and make it more robust with proper test case and check an error there before implementing into a production environment.
Now you can solve your code error in less than a minute.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button