If I have a list:


Is there a function that allows me to easily construct a list that shows the intervals between elements:


I know I can shift the list then subtract (like below), but I am not sure whether there is a single function that would allow me to do it:




closed as off-topic by MarcoB, m_goldberg, march, Carl Lange, Alex Trounev May 8 at 0:21

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – MarcoB, m_goldberg, march, Carl Lange, Alex Trounev
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 6
    $\begingroup$ Use Differences $\endgroup$ – MarcoB May 6 at 15:17
  • $\begingroup$ Awesome! Thanks! $\endgroup$ – baker May 6 at 15:19
  • $\begingroup$ Differences[L] is fine, as @MarcoB says; but for top speed I was surprised to find that Rest[L]-Most[L] is a bit faster. $\endgroup$ – Roman May 6 at 15:58

As @MarcoB says, Differences is the canonical way to go:

L = Sort@RandomReal[{0, 1}, 10^7];
d1 = Differences[L]; // RepeatedTiming // First
(* 0.20 *)

Rest-Most is twice as fast though, which I find very strange:

d2 = Rest[L] - Most[L]; // RepeatedTiming // First
(* 0.090 *)

BlockMap is a terrible idea:

d3 = BlockMap[#[[2]] - #[[1]] &, L, 2, 1]; // RepeatedTiming // First
(* 4.60 *)

All methods agree on the result though:

d1 == d2 == d3
(* True *)
  • 2
    $\begingroup$ The nice thing about Differences is the ease in using the second parameter to get differences of differences, and so on (wonder if the Rest/Most approach still holds out as better in that case). $\endgroup$ – MikeY May 6 at 18:59
  • 2
    $\begingroup$ @MikeY yes it's still faster: Differences[L, 2] takes 0.36 seconds and L[[3 ;;]] + L[[;; -3]] - 2 L[[2 ;; -2]] takes only 0.25 seconds. $\endgroup$ – Roman May 6 at 20:03

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