Dividing enumerable by corresponding index in another

Hi,

What would be the recommended way to divide every item in an enumerable, in this case a list, by every item at the corresponding index of another list. Would like to return a new list with the result.

ie:
list1 = [10,20,30,40]
list2 = [1,2,3,4]

new_list = [10, 10, 10, 10]

Have tried a few things with nested comprehensions and also with a Enum.map within an Enum.map but it got really convoluted… Anyone have any ideas???

thank you!

1 Like

Maybe this

Enum.zip(list1, list2) |> Enum.map(fn {x, y} -> div(x, y) end)

or this, but You will get float in return :slight_smile:

Enum.zip(list1, list2) |> Enum.map(fn {x, y} -> x / y end)

and beware of having list1 and list2 with the same number of elements, otherwise You may have shortened result.

Not to mention divide by 0 error.

3 Likes