#How to create a two-dimensional list in python?
How to create a two-dimensional list in python:
Two methods of creating a two-dimensional list in python
Method one:
Use numpy-zeros((10,10)) to generate a two-dimensional list of a given length.
Method 2:
Use for loop to avoid shallow copy
Python creates a two-dimensional list by looping. The code is as follows:
In this way, a 10*10 two-dimensional list with a default value of 0 is created. The method to implement the same list is b=[[0]*10]*10, and When judging a==b, the return value is True. However, there are certain problems with the list created by this method. When we set b[0][1]=1, our original intention is to only change the value of one item in the list, but in fact it is not:
We found that the second column of the entire list has changed. This is because [[]]*10 represents 10 references to the elements of this empty list, which is a shallow Copy, so modifying any element will change the entire list, so we need to take a third way to create a two-dimensional list:
When we let c[0][1 ]=1, only changes the value of one item in the list, which meets our requirements for creating a two-dimensional list
Recommended tutorial: "python video tutorial"
The above is the detailed content of How to create a two-dimensional list in python?. For more information, please follow other related articles on the PHP Chinese website!