Home >Backend Development >Python Tutorial >How to reference arrays in Python lists
This article introduces Python lists. In computer languages, Python lists are a widely used language. If you have some questions about the practical application skills of Python lists, you can browse our articles below. It is an introduction to the content of the article.
There is no data structure for arrays in Python, but lists are very similar to arrays, such as:
a=[0,1,2]这时a[0]=0, a[1]=1, a[[2]=2,
But it raises a question, that is, what to do if array a wants to be defined from 0 to 999, in which case a = range(0, 1000 )accomplish. Or omit it as a = range(1000). If you want to define a with a length of 1000 and the initial values are all 0, then
a = [0 for x in range(0, 1000)]
here defines a 10*10 two-dimensional array with an initial value of 0. Later, I found a simpler method of literal two-dimensional array on the Internet: b = [[0]*10]*10, defining 10*10 as a two-dimensional array with an initial value of 0. Compare with
a=[[0 for x in range(10)] for y in range(10)]
: the result of print a==b is True. However, after using the definition method of b instead of a, the previous program that could run normally also went wrong. After careful analysis, the difference was found: when a[0][0]=1, only a[0][0] is 1, All others are 0. When b[0][0]=1, a[0][0], a[1][0], and 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. Therefore, b = [[0]*10]*10 does not conform to our conventional two-dimensional array.
After testing at the same time: the definition of c=[0]*10 has the same effect as c=[0 for x in range(10)], without the problem of the same reference above. It is estimated that the definition of array c is a value type Multiply, and the previous b uses type multiplication, because the one-dimensional array is a reference (borrowing the value type and reference type in C#, I don’t know if it is appropriate). The above article is a partial introduction to Python lists.
The above is how to reference arrays in Python lists. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!