-4

I thought Python (numpy) is zero indexing, but when I slice [:0] it returns empty array. I thought I'm saying slice from zero to zero but clearly I am not.

If instead I use A[1] it returns the position 1 element of by zero-indexing.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
monotonic
  • 394
  • 4
  • 20
  • 3
    `np.array([1,2,3,4])[:1]` evaluates to `array([1])`, not an empty array. Perhaps your array is already empty? – DYZ Feb 19 '18 at 08:09
  • 3
    Please give a [mcve] that recreates this; on a non-empty array (or vanilla list) `A[:1]` should give you the zeroth element. – jonrsharpe Feb 19 '18 at 08:10
  • to fix a vector v of shape (,100) problem, you can do `v = v.reshape(1,len(v)) `, or use double brackets when creating your vectors. – Emmet B Feb 19 '18 at 08:14
  • Python and numpy are definitely zero-based. Slice endpoints are *exclusive*, `[:0]` is *"up to but not including zero"*, which is obviously empty. If you want the zeroth element, just use `[0]`. – jonrsharpe Feb 19 '18 at 08:44
  • @jonrsharpe why not including..? – monotonic Feb 19 '18 at 08:51
  • See e.g. https://stackoverflow.com/q/11364533/3001761 – jonrsharpe Feb 19 '18 at 08:54
  • 1
    Not including because that way `mylist[:x] + mylist[x:] == mylist` – BoarGules Feb 19 '18 at 09:08
  • Why not including? Do you want `range(10)` to produce 10 numbers or 11? `[0,1,2...9]` or `[0,1,2,...,9,10]`? – hpaulj Feb 19 '18 at 18:02

1 Answers1

-1

When using slice it excludes the endpoint, just like in range(a, b) = a..(b-1)

Though when you do list[:1] it should return [list[0]], not an empty array. Thus I suspect that your array is empty from the beginning.

Reference

Gareth Ma
  • 329
  • 2
  • 11