Divide one list of numbers by another list in Python

avatar

Borislav Hadzhiev

Last updated: Jul 11, 2022

banner

Photo from Unsplash

Divide one list of numbers by another list in Python #

To divide one list of numbers by another list:

  1. Use the zip function to get an iterable of tuples with the corresponding items.
  2. Use a list comprehension to iterate over the iterable.
  3. On each iteration, divide the values in the current tuple.
main.py
list_1 = [10, 30, 60] list_2 = [2, 3, 10] new_list = [x / y for x, y in zip(list_1, list_2)] print(new_list) # 👉️ [5.0, 10.0, 6.0]

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

main.py
list_1 = [10, 30, 60] list_2 = [2, 3, 10] # 👇️ [(10, 2), (30, 3), (60, 10)] print(list(zip(list_1, list_2)))

You can imagine that the zip() function iterates over the lists, taking 1 item from each.

The first tuple in the list consists of the elements in each list with an index of 0, the second tuple consists of the elements in each list that have an index of 1, etc.

The last step is to use a list comprehension to iterate over the zip object and divide the values in each tuple.

main.py
list_1 = [10, 30, 60] list_2 = [2, 3, 10] # 👇️ [(10, 2), (30, 3), (60, 10)] print(list(zip(list_1, list_2))) new_list = [x / y for x, y in zip(list_1, list_2)] print(new_list) # 👉️ [5.0, 10.0, 6.0]
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we unpack the values from the tuple and use the division / operator to divide them.

main.py
x, y = (10, 2) print(x) # 👉️ 10 print(y) # 👉️ 2

Alternatively, you can use the map() function.

Divide one list of numbers by another list using map() #

To divide one list of numbers by another list:

  1. Use the map() function to call the truediv() function with the two lists.
  2. Use the list() class to convert the map object to a list.
main.py
from operator import truediv list_1 = [10, 30, 60] list_2 = [2, 3, 10] result = list(map(truediv, list_1, list_2)) print(result) # 👉️ [5.0, 10.0, 6.0]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The truediv function from the operator module is the same as a / b.

You can imagine that map calls the truediv function with each item of the two iterables (e.g. items at index 0, then 1, etc).

The map function returns a map object, so we had to use the list() class to convert the result to a list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.