Home  >  Article  >  Backend Development  >  How to create a two-dimensional list in python?

How to create a two-dimensional list in python?

coldplay.xixi
coldplay.xixiOriginal
2020-06-15 14:14:0313200browse

How to create a two-dimensional list in python?

#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:

How to create a two-dimensional list in python?

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:

How to create a two-dimensional list in python?

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:

How to create a two-dimensional list in python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn