-1

Consider this code:

>>> arr = np.array(['A', 'B', 'C'])
>>> arr[0:20]
array(['A', 'B', 'C'], 
      dtype='|S1')

Why am I allowed to slice the array past 3? I expected this to throw an an error, as there are not 20 entries to reference.

kilojoules
  • 9,768
  • 18
  • 77
  • 149
  • 2
    This behavior is consistent with Python list slicing: https://stackoverflow.com/questions/509211/explain-slice-notation – DYZ Jun 19 '17 at 22:52
  • 1
    Answers to why questions like this require finding explanations in the development discussions. Since this has been part of `numpy` and `python` for a long time, it will hard to find that. It could predate the modern use of `github` and `PEP's`. – hpaulj Jun 19 '17 at 23:14
  • 1
    Heck, it predates the old Mercurial repository, and maybe the Subversion repo. – user2357112 Jun 19 '17 at 23:21

2 Answers2

1

That works for regular list slicing too, and string slicing, and tuple slicing, and most sliceable objects. It's just the Python convention to allow out-of-range slicing and adjust out-of-range slice endpoints to the nearest endpoint of the sequence.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

This is taken from the documentation.

Given a slice expression like s[i:j:k],

The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater

The same applies to numpy arrays. Given a slice expression, say x[0:20], it'll just be reduced to x[0:len(x)] returning everything in the array.

Python gracefully handles out of bounds access to elements by returning as many elements as there are without throwing an error. This is a design decision taken by the developers of the language. You may or may not want the error, so do be cautious when slicing lists this way.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • This doesn't answer my question. Why is it designed this way? It seems better to throw an error. – kilojoules Jun 19 '17 at 22:54
  • @kilojoules It is how python gracefully handles such situations _without_ throwing ugly out of bounds exceptions like other languages. It is how python was designed. – cs95 Jun 19 '17 at 22:55
  • I'm having trouble understanding the design decision. What are the benefits of doing things this way? – kilojoules Jun 19 '17 at 23:15
  • @kilojoules I'm sorry... There is no official statement I am aware of, but I do believe it makes for more robust programming with the unintentional side effect now and then. – cs95 Jun 19 '17 at 23:16