Describes how to use the Sequence type in Python3, python3sequence
In fact, it was intended to reverse the list. I checked the meaning of list [:-1] and found that there are still many points to pay attention.
Is the main reference https://docs.python.org/3/library/stdtypes.html? Highlight = list # list
First, there are three Sequence types.
- List
- Tuple
- Range
Slice
[I: j: k] indicates slice of s from I to j with step k, which is useful for all three types.
>>> a = [1, 2, 3]>>> a[::-1][3, 2, 1]>>> a = (1, 2, 3)>>> a[::-1](3, 2, 1)>>> a = range(3)>>> a[::-1]range(2, -1, -1)
The parameter in range is range (start, stop [, step]).
Initialize a list
S * n indicates n shallow copies of s concatenated.
Note that it is a light copy, so the following situations may occur:
>>> lists = [[]] * 3>>> lists[[], [], []]>>> lists[0].append(3)>>> lists[[3], [3], [3]]
It doesn't matter if the element is not an object.
>>> lists = [0] * 3>>> lists[0, 0, 0]>>> lists[0] = 1>>> lists[1, 0, 0]
The correct method for initializing the nested list should be
>>> lists = [[] for i in range(3)]>>> lists[0].append(3)>>> lists[1].append(5)>>> lists[2].append(7)>>> lists[[3], [5], [7]]
Concatenation pitfall
(I think it is clearer in English. This is the same as Java)
Concatenating immutable sequences always results in a new object. this means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. to get a linear runtime cost, you must switch to one of the alternatives below: