What meaning is 'a[0:10:2]'?
Steven D'Aprano
steve at pearwood.info
Mon Nov 16 07:29:08 EST 2015
On Mon, 16 Nov 2015 11:27 am, fl wrote:
> hi,
>
> When I learn slice, I have a new question on the help file. If I set:
>
> pp=a[0:10:2]
>
> pp is array([1, 3])
Really? How do you get that answer? What is `a`?
> I don't know how a[0:10:2] gives array([1, 3]).
Neither do I, because you have not told us what `a` is.
But I know what `a[0:10:2]` *should* be:
it takes a copy of elements from a, starting at position 0, ending just
before position 10, and taking every second one.
py> a = list(range(100, 121))
py> print(a)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120]
py> print(a[0:10])
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
py> print(a[0:10:2])
[100, 102, 104, 106, 108]
py> print(a[0:10:3])
[100, 103, 106, 109]
By default, the first item is automatically 0, so these two slices are the
same:
a[0:10:2]
a[:10:2]
If the start or end position are out of range, the slice will only include
positions that actually exist:
py> a[:10000:5]
[100, 105, 110, 115, 120]
--
Steven
More information about the Python-list
mailing list