x=[1,2,3,4]
In [91]: x[:1]
Out[91]: [1]
x[:n] select up to 'n' (exclusive) columns?
In [93]: x[:-1]
Out[93]: [1, 2, 3]
How does x[:-1]
work?
In [94]: x[::-1]
Out[94]: [4, 3, 2, 1]
And what about x[::-1]
? There are two ::
here.
x=[1,2,3,4]
In [91]: x[:1]
Out[91]: [1]
x[:n] select up to 'n' (exclusive) columns?
In [93]: x[:-1]
Out[93]: [1, 2, 3]
How does x[:-1]
work?
In [94]: x[::-1]
Out[94]: [4, 3, 2, 1]
And what about x[::-1]
? There are two ::
here.
x[:1]
gets the all the values that index is smaller than 1
(so basically just get zeroth element)
x[:-1]
gets all values until last value
x[::-1]
reverses the list
You can imagine Python slice x[start:end]
as an interval [start, end)
. Besides, missed sign can be 0
or len(x)
.
x = [1, 2, 3, 4]
x[:1]
is x[0:1]
and it's [0]
x[:-1]
is x[0:len(x)-1]
and it's [1, 2, 3]
x[::-1]
is a reversed x and it's [4, 3, 2, 1]
x[start:stop:step]
is the basic format
If any of the three are not specified, they take the default values, start = 0, stop = just after last element, step = 1
According to string indexing, x[1] is the second index and x[-1] is the last index.