Home > Backend Development > Python Tutorial > How to define an array in python

How to define an array in python

coldplay.xixi
Release: 2023-01-03 09:28:10
Original
82939 people have browsed it

How to define arrays in python: 1. Directly define [a=[[1,1],[1,1]]]; 2. Indirectly define [a=[[0 for x in range(10 )] for y in range(10)]]; 3. [b = [[0]*10]*10] A two-dimensional array of initial 0.

How to define an array in python

The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.

How to define an array in Python:

There is no data structure for arrays in Python, but lists are very similar to arrays, such as:

a=[0,1,2], then a[0]=0, a[1]=1, a[[2]=2, but it raises a question, that is, if the array a wants to be defined as 0 to What to do with 999? This may be achieved through a = range(0, 1000). Or omitted as a = range(1000). If you want to define a of length 1000, and the initial values ​​are all 0, then a = [0 for x in range(0, 1000)]

The following is Definition of two-dimensional array:

Directly define a=[[1,1],[1,1]], here a 2*2 is defined, and the initial A two-dimensional array of 0.

Indirect definition a=[[0 for x in range(10)] for y in range(10)], here defines a 10*10 two-dimensional array with an initial value of 0.

There is also a simpler method of literal two-dimensional array:

b = [[0]*10]*10, definition 10 *10A two-dimensional array initially initialized with 0.

Compare with a=[[0 for x in range(10)] for y in range(10)]: the result of print a==b is True.

But after using the definition method of b instead of a, the program that could run normally before also went wrong. After careful analysis, the difference was found:

  • a[0] When [0]=1, only a[0][0] is 1, and the others are all 0.

  • When b[0][0]=1, a[0][0], a[1][0], until a[9,0] are all 1 .

From this we get that the 10 small one-dimensional data in the large array all have the same reference, that is, they point to the same address.

So b = [[0]*10]*10 does not conform to our conventional two-dimensional array.

Related free learning recommendations: python video tutorial

The above is the detailed content of How to define an array in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template