# Loop function over list [duplicate]

I would like to divide element 1 of a list by element 2; element 2 by element 3, and so on. What is the best way of doing this?

I have tried

f = #1/#2 &


Have a feeling I might have to use Do, or Reap / Sow but don't have any programming background, so coming unstuck.

-

## marked as duplicate by Kuba, belisarius, bobthechemist, Sjoerd C. de Vries, Michael E2Dec 19 '13 at 0:55

Ratios is almost your friend :) –  Öskå Dec 18 '13 at 15:46
@ Öskå - thanks - indeed it is! –  martin Dec 18 '13 at 15:48
1/# & /@ Ratios@list is even more your friend ;o) –  Öskå Dec 18 '13 at 15:50
@Öskå, or maybe just 1/Ratios@list –  Simon Woods Dec 18 '13 at 15:54
Completing OP's form: f = (#1/#2 &) @@@ Partition[#, 2, 1] & –  Chris Degnen Dec 18 '13 at 17:23

Operations on adjacent pairs of elements comes up often in , although I can't recall a specific question on this. Sometimes you get lucky with a built in function like Ratios or Differences that does exactly what you want. But what if there isn't a built-in function for your specific need?

The idiom you need to remember that will be useful for any arbitrary function (not just division or subtraction) is to use Most and Rest:

list = Range@10;
Most@list/Rest@list
(* {1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9, 9/10} *)

-
Worth to mention that Partition[list,2,1] may be useful but in this case it is longer. Maybe the title can be changed so it will become a refference Q&A for operations on adjacent elements? –  Kuba Dec 18 '13 at 16:43

Just for comparison:

list = Range[1000];

Do[ Divide @@@ Partition[list, 2, 1]                     , {1000}] // Timing // First
Do[ 1/Ratios@list                                        , {1000}] // Timing // First
Do[ Most@list/Rest@list                                  , {1000}] // Timing // First
Do[ #/#2 & @@@ Partition[list, 2, 1]                     , {1000}] // Timing // First
Do[ DeveloperPartitionMap[Divide @@ # &, list, 2, 1]    , {1000}] // Timing // First
Do[ #[[1]]/#[[2]] & /@ Partition[list, 2, 1]             , {1000}] // Timing // First
Do[ DeveloperPartitionMap[#[[1]]/#[[2]] &, list, 2, 1]  , {1000}] // Timing // First

1.045207
1.154407
0.982806
2.402415
3.151220
4.196427
4.087226

-
Most[#1/#2] &[list, RotateLeft[list]]

-