0
a = np.ramdon.rand(10)

# We can index a numpy array by [start:stop(:step)]

a[::1]  # returns [a[0], a[1], ..., a[9]]
a[::-1]  # returns [a[9], a[8], ..., a[0]]

As shown in the above example, start and stop for both a[::1] and a[::-1] should be by default, since only the step arguments are given. For a[::1], I suppose the default start should be 0 and the default stop should be -1 (i.e., a[::1] is the same as a[0:-1:1]), but apparently this is not true for a[::-1], since a[0:-1:-1] returns an empty array. So what are the exact default setting for stop and start? I am so confused because all the documentations I ran into only mentioned that to reverse an array you can use ::-1 with no further explanation.

Yu Gu
  • 2,382
  • 5
  • 18
  • 33
  • 2
    All the defaults are `None`... you can just do `something[:]` or `something[::]` for instance... basically if start is `None` then it's 0 and if end is `None` it's considered `len(obj)` and step if not given defaults to 1... – Jon Clements Jan 27 '20 at 03:55
  • 1
    However, if step is negative, then have a look at https://stackoverflow.com/questions/59920270/how-to-read-slicing-with-negative-step/59920309#59920309 – Jon Clements Jan 27 '20 at 03:57
  • eg: if you had a list `r = list(range(20))` - then you can take every third element just using `r[::3]`... (which'll give you `[0, 3, 6, 9, 12, 15, 18]`) and then you could use `[::-1]` on that to reverse it, but if you wanted to do stepping backwards to begin with you'd need to do `r[-2::-3]` – Jon Clements Jan 27 '20 at 04:07
  • @JonClements So when the step is negative, it counts down from the last element by default when `start` is not given, while when the step is positive, it counts up from the first element by default, right? – Yu Gu Jan 27 '20 at 04:10
  • Depends what `end` is set as :) Looks like you've got some good links to read though... most of it is quite intuitive - the bits that aren't immediately you'll never really have to worry about anyway. – Jon Clements Jan 27 '20 at 04:18
  • @JonClements I just read those links. Based on my current understanding, I think it actually has nothing to do with the `end`. If the `start` is not given, for a positive `step`, the `start` is by default 0, and for a negative `step`, it's by default -1. – Yu Gu Jan 27 '20 at 05:07
  • 1
    Put simply, the default is the value that gives the maximum range - the `whole` thing if the user doesn't limit it. – hpaulj Jan 27 '20 at 05:44
  • @hpaulj This interpretation is pretty clear. – Yu Gu Jan 27 '20 at 15:26

0 Answers0