Python learning: list, python learning list
First:
Note:
A built-in data type in Python is list: list. List is an ordered set that allows you to add and delete elements at any time.
For example, you can use a list to list the names of all the students in the class:
>>> classmates = ['Michael', 'Bob', 'Tracy']>>> classmates['Michael', 'Bob', 'Tracy']
Variableclassmates
Is a list. Uselen()
The function can obtain the number of list elements:
>>> len(classmates)3
Use indexes to access the elements at every position in the list. Remember that the index is from0
Start:
>>> classmates[0]'Michael'>>> classmates[1]'Bob'>>> classmates[2]'Tracy'>>> classmates[3]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range
When the index is out of the range, Python will report an IndexError. Therefore, make sure that the index does not cross the border. Remember that the index of the last element islen(classmates) - 1
.
To obtain the last element, you can use-1
Index to directly obtain the last element:
>>> classmates[-1]'Tracy'
And so on, you can get 2nd to the last and 3rd to the last:
>>> classmates[-2]'Bob'>>> classmates[-3]'Michael'>>> classmates[-4]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range
Of course, the last 4th will be out of the border.
List is a variable ordered table. Therefore, you can append an element to the end of the list:
>>> classmates.append('Adam')>>> classmates['Michael', 'Bob', 'Tracy', 'Adam']
Try
You can also insert an element to a specified position, for example, index number1
Location:
>>> classmates.insert(1, 'Jack')>>> classmates['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
To delete the element at the end of the list, usepop()
Method:
>>> classmates.pop()'Adam'>>> classmates['Michael', 'Jack', 'Bob', 'Tracy']
To delete the element at the specified position, usepop(i)
Method, wherei
Is the index location:
>>> classmates.pop(1)'Jack'>>> classmates['Michael', 'Bob', 'Tracy']
To replace an element with another element, you can directly assign a value to the corresponding index location:
>>> classmates[1] = 'Sarah'>>> classmates['Michael', 'Sarah', 'Tracy']
The Data Types of the elements in the list can also be different, for example:
>>> L = ['Apple', 123, True]
The list element can also be another list, for example:
>>> s = ['python', 'java', ['asp', 'php'], 'scheme']>>> len(s)4
Note:s
There are only four elements, of whichs[2]
It is also a list, which is easier to understand if it is split and written:
>>> p = ['asp', 'php']>>> s = ['python', 'java', p, 'scheme']
To get'php'
Writablep[1]
Ors[2][1]
, Sos
It can be seen as a two-dimensional array, similar to 3D, four-dimensional ...... Array, but rarely used.
If no element exists in a list, it is an empty list with a length of 0:
>>> L = []>>> len(L)0