Divide all Elements of a List by a Number in Python
The task of dividing all elements of a list by a number in Python involves iterating over the list and applying the division operation to each element. For example, given a list a = [14, 8, 0, 12, 981, 21, -99] and a divisor d = 7, the result after dividing each element by 7 will be [2, 1, 0, 1, 140, 3, -14].
Using list comprehension
List comprehension is one of the most efficient way to transform elements of a list. It provides a concise syntax for iterating over the list and performing operations, such as dividing each element by a number. This method creates a new list by applying the operation to each element in a single, readable line of code.
a = [14, 8, 0, 12, 981, 21, -99]
d = 7 # divisor
res = [x // d for x in a]
print(res)
Output
[2, 1, 0, 1, 140, 3, -15]
Explanation: list comprehension iterate over each element x in the list a and performs integer division // of each element by d . The results are collected into a new list res .
Table of Content
Using map()
When dividing all elements of a list by a number, map() can be combined with a lambda function for an efficient transformation. This method avoids the overhead of explicitly iterating over the list using a loop, but it can be slightly less efficient than list comprehension, especially for simple operations.
a = [14, 8, 0, 12, 981, 21, -99]
d = 7
res = list(map(lambda x: x // d, a))
print(res)
Output
[2, 1, 0, 1, 140, 3, -15]
Explanation: map() apply integer division x // d to each element in the list a using a lambda function, and then converts the result into a list with list().
Using for loop
In this method, we explicitly iterate over each item in the list and perform the division operation, appending the result to a new list. While this method works fine for smaller lists, it introduces additional overhead with each loop iteration and append() operation, making it less efficient for larger datasets.
a = [14, 8, 0, 12, 981, 21, -99]
d = 7 # divisor
res = [] # initialize empty list
for x in a:
res.append(x // d)
print(res)
Output
[2, 1, 0, 1, 140, 3, -15]
Explanation: for loop iterate over each element x in the list a. For each element, it performs integer division x // d , dividing x by d and appends the result to the res list.
Using Numpy
When working with large datasets, using NumPy for dividing all elements of a list by a number can be highly efficient, as NumPy performs operations using vectorization techniques. This allows us to apply the division operation across the entire array in a single, highly optimized step, reducing the computational overhead compared to lists.
import numpy as np
a = [14, 8, 0, 12, 981, 21, -99]
d = 7 # divisor
a_np = np.array(a) # Convert `a` into NumPy array
res = a_np // d
print(res)
Output
[ 2 1 0 1 140 3 -15]
Explanation: This code imports NumPy, converts the list a into a NumPy array a_np and performs integer division // of each element by the divisor d. The result is stored in res .