Python basics-list, python-list
List is an ordered set that allows you to add and delete elements at any time.
Knowledge point:
| Add |
Append (),. insert () |
| Delete |
. Pop (1) |
| Query |
Classmates [-1] |
| Change |
Classmates [1] = 'sara' |
| Additional |
S = ['python', 'java', ['asp ', 'php'], 'scheme'], s [2] [1] |
.
Create:
>>> classmates = ['Michael', 'Bob', 'Tracy']>>> classmates['Michael', 'Bob', 'Tracy']
|
Add:
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']
You can also insert an element to a specified position, for example, index number1Location: >>> classmates.insert(1, 'Jack')>>> classmates['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
|
Delete:
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, whereiIs the index location: >>> classmates.pop(1)'Jack'>>> classmates['Michael', 'Bob', 'Tracy']
|
Query:
>>> len(classmates) 3
>>> classmates[0]'Michael'>>> classmates[1]'Bob'>>> classmates[2]'Tracy'>>> classmates[3]Traceback (most recent call last): File "<stdin>", line 1, in <module
>>> 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. |
Change:
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']
|
Additional:
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:sThere 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], SosIt 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