3
$\begingroup$

I could not find something similar.

Given, e.g.

lst = Range[10]
(* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} *)

the following gives the reverse of lst (I know about Reverse).

lst[[-1 ;; 1 ;; -1]]
(* {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} *)

Why the following does not return the same output?

lst[[;; ;; -1]]

Thanks.

$\endgroup$
4
  • $\begingroup$ @Kuba. This means that I have to provide the starting point to Span, right? Otherwise it starts by default from the beginning. Is there any similar concept to Mathematica with Python's slicing? (Thanks for the commenf by the way!) $\endgroup$
    – Dimitris
    Apr 9, 2017 at 22:01
  • $\begingroup$ What is the difference between Mathematica's Span and Part compared to Python's slicing? So far you have only shown that Mathematica uses a slightly different syntax. $\endgroup$
    – C. E.
    Apr 9, 2017 at 22:32
  • $\begingroup$ @C.E. For instance lst[::-1] gives the lst reversed without prividing any start/end value. $\endgroup$
    – Dimitris
    Apr 9, 2017 at 22:37
  • 2
    $\begingroup$ It seems that the syntax sugar for reverse is the only difference between the two. Since Span defaults start position to 1 and end position to All it cannot use ;; ;; -1 to produce the list reversed. See ;; ;; -1 // InputForm. $\endgroup$
    – Edmund
    Apr 9, 2017 at 23:38

1 Answer 1

3
$\begingroup$

If you evaluate

;; ;; -1

you get

1 ;; All ;; -1

This shows that the default starting point is always 1, regardless of the step size. Note that ;; is short for Span. Generally, the default for a given argument of Span is independent of the other arguments. The default for the first one (beginning) is always 1, the second one (end) always All and the third one (step size) 1.

;; ;; -1 will not work because if we start at 1, we cannot count downwards without hitting the boundary of the array.

$\endgroup$
3
  • $\begingroup$ It is explicitly documented (emphasis is mine): ";;;;k represents a span from the beginning to the end in steps of k." It is the last point before the "Details" section on the Docs page for Span. $\endgroup$ Apr 10, 2017 at 16:08
  • $\begingroup$ ... but the construct ;; ;; -1 is parsed as a whole, and not as a combination of two Spans. It can be seen from comparing it with ;; ;; ;; -1 and with ( ;; ) (;; -1), and also with ToExpression[";;;;-1", InputForm, HoldComplete]. Tangentially related: (123359). $\endgroup$ Apr 10, 2017 at 16:21
  • $\begingroup$ @AlexeyPopkov I did not mean to say that it could not be any other way. $\endgroup$
    – Szabolcs
    Apr 10, 2017 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.