1.list
Python will report a indexerror error when the index is out of range, so make sure the index is not out of bounds and remember that the index of the last element is len(classmates) - 1
.
The list is a mutable, ordered table, so you can append an element to the end of the list:
>>> classmates.append(‘Adam‘)>>> classmates[‘Michael‘, ‘Bob‘, ‘Tracy‘, ‘Adam‘]
You can also insert elements into the specified position, such as the index number 1
:
>>> classmates.insert(1, ‘Jack‘)>>> classmates[‘Michael‘, ‘Jack‘, ‘Bob‘, ‘Tracy‘, ‘Adam‘]
To delete the element at the end of the list, use the pop()
method:
>>> classmates.pop()‘Adam‘>>> classmates[‘Michael‘, ‘Jack‘, ‘Bob‘, ‘Tracy‘]
To delete an element at a specified location, using the pop(i)
method, where the i
index is located:
>>> classmates.pop(1)‘Jack‘>>> classmates[‘Michael‘, ‘Bob‘, ‘Tracy‘]
To replace an element with another element, you can assign a value directly to the corresponding index position:
>>> classmates[1] = ‘Sarah‘>>> classmates[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
The data types of the elements in the list can also be different, such as:
>>> L = [‘Apple‘, 123, True]
The list element can also be another list, such as:
>>> s = [‘python‘, ‘java‘, [‘asp‘, ‘php‘], ‘scheme‘]>>> len(s)4
Note that s
there are only 4 elements, one of which s[2]
is a list, which is easier to understand if it is disassembled:
>>> p = [‘asp‘, ‘php‘]>>> s = [‘python‘, ‘java‘, p, ‘scheme‘]
To get ‘php‘
can write p[1]
or s[2][1]
, therefore s
can be regarded as a two-dimensional array, similar to three-dimensional, four-dimension ... arrays, but rarely used.
If a list does not have an element, it is an empty list with a length of 0:
>>> L = []>>> len(L)0
2.tuple
The trap of a tuple: when you define a tuple, the elements of a tuple must be determined when defined, such as:
>>> t = (1, 2)>>> t(1, 2)
If you want to define an empty tuple, you can write ()
:
>>> t = ()>>> t()
However, to define a tuple with only 1 elements, if you define this:
>>> t = (1)>>> t1
The definition is not a tuple, it is 1
this number! This is because the parentheses ()
can represent both tuple and parentheses in the mathematical equation, which creates ambiguity, so Python rules that, in this case, the parentheses are calculated, and the result is naturally 1
.
Therefore, only 1 elements of a tuple definition must be added with a comma ,
to disambiguate:
>>> t = (1,)>>> t(1,)
Python will also add a comma when displaying a tuple of only 1 elements, ,
lest you misunderstand the parentheses in the mathematical sense.
Learn Liao python notes-strings and encodings