Divide the first element of a list by the second and third by the fourth and so on

advertisements

Currently I have 2 lists which I divide by each other

a = [5,6,7,8]
b = [100,200,300,400]
output = [b/m for b,m in zip(a,b)]

However due to the nature of my database it is faster to retrieve list a and b differently:

data = [5,100,6,200,7,300,8,400]

The first value in the list is the first value in a, the second value the first value in b, the third value the second value in a and so on.

output = [5/100,6/200,7/300,8/400]

Thus I need to divide the first value by the second and the third by the fourth and so on. Now this is no problem, but I need it to be as fast as possible. Any suggestions?


You can use slicing for this:

output = [b / m for b, m in zip(data[::2], data[1::2])]

Edit 3: What we have now (len(data) = 8000):

  1. The iter solution by Jon Clements with ~1ms
  2. The normal slicing solution with 1.1ms
  3. The range solution with 2.5ms
  4. The map solution (materialising it using list) with 2.7ms