What meaning is 'a[0:10:2]'?
Tim Chase
python.list at tim.thechases.com
Sun Nov 15 19:48:04 EST 2015
On 2015-11-15 16:27, fl wrote:
> 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])
>
> I don't know how a[0:10:2] gives array([1, 3]).
>
> I know matlab a lot, but here it seems quite different. Could you
> tell me what meaning a[0:10:2] is?
Well, if it a matlab.array was a well-behaved object it would just
give you "0". As your copy/paste on the help for a slice stated, the
first number is where it starts (0), the second number is where it
ends (10, exclusive), and the 3rd number (2) is the stride. To
demonstrate:
>>> a = list(range(20))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[0:10:2]
[0, 2, 4, 6, 8]
>>> a[:10:2]
[0, 2, 4, 6, 8]
>>> a[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
So note that the stride of 2 provides every other one while a stride
of three provides every 3rd value
>>> a[0:10:3]
[0, 3, 6, 9]
-tkc
More information about the Python-list
mailing list