Summary: The most Pythonic approach to divide each element in a list is to use the following list comprehension: [element/divisor for element in given_list]
.
Read ahead to discover numerous other solutions.
Problem: How to divide each element in a list and return a resultant list containing the quotients?
Example:
li = [38, 57, 76, 95, 114, 161.5] num = 19 # Some way to divide each element of li with 19
Expected Output:
[2.0, 3.0, 4.0, 5.0, 6.0, 8.5]
So, without further delay, let us dive into the mission-critical question and find out the different ways of solving it.
Video Walkthrough
Method 1: Using a For Loop
Approach:
- Create an empty list that will store the quotients.
- Iterate across all the elements in the given list using a for loop.
- Divide each element with the given number/divisor and append the result in the resultant list.
- Finally, display the resultant list after all the quotients have been calculated and appended to it.
Code:
li = [38, 57, 76, 95, 114, 161.5] num = 19 res = [] for val in li: res.append(val/num) print(res)
Output:
[2.0, 3.0, 4.0, 5.0, 6.0, 8.5]
๐Read Here: Python Loops
Method 2: Using a List Comprehension
Let’s dive into the most Pythonic solution to the given problem.
Approach: Create a list comprehension such that:
- The Expression:
a/num
represents the division of each element in the list by the given divisor. Here the context variablea
represents each element in the given list whilenum
represents the divisor. - The Context: The context contains the context variable
a
, which ranges across all the elements within the list such that in each iteration, it represents an element at a particular index at that iteration.
Code:
li = [38, 57, 76, 95, 114, 161.5] num = 19 res = [a/num for a in li] print(res)
Output:
[2.0, 3.0, 4.0, 5.0, 6.0, 8.5]
๐A quick recap to List Comprehensions in Python:
List comprehension is a compact way of creating lists. The simple formula is [expression + context]
.
โฆฟ Expression: What to do with each list element?
โฆฟ Context: What elements to select? The context consists of an arbitrary number of for
and if
statements.
โฆฟ The example [x for x in range(3)]
creates the list [0, 1, 2]
.
๐Recommended Read: List Comprehension in Python โ A Helpful Illustrated Guide
Method 3: Using map and lambda
Approach: The idea here is to use an anonymous lambda
function to calculate the division of each element with the given divisor. You can pass each element of the list to the lambda
function as an input with the help of the built-in map
function.
Code:
li = [38, 57, 76, 95, 114, 161.5] num = 19 res = list(map(lambda x: x/num, li)) print(res)
Output:
[2.0, 3.0, 4.0, 5.0, 6.0, 8.5]
๐Readers Digest:
- The
map()
function transforms one or more iterables into a new one by applying a โtransformator functionโ to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. If you pass n iterables as arguments, the transformator function must be an n-ary function taking n input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.
๐Read more about map()
here: Python map() โ Finally Mastering the Python Map Function [+Video]
- A lambda function is an anonymous function in Python. It starts with the keyword
lambda
, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example,lambda x, y, z: x+y+z
would calculate the sum of the three argument valuesx+y+z
.
๐Read more about map()
here: Lambda Functions in Python: A Simple Introduction
Method 4: Using Numpy
Another simple workaround for the given problem is to use the Numpy
library. Here you have two options or approaches that will help you to deduce the output.
4.1 Using division / operator
- Convert the given list to a
Numpy
array usingnp.array
method. - Divide each element of this array with the given divisor using the division operator “/”.
- To generate the resultant list from the output array you can use the
ndarray.tolist()
method.
Code:
import numpy as np li = [38, 57, 76, 95, 114, 161.5] arr = np.array(li) num = 19 res = arr/num print(res.tolist())
Output:
[2.0, 3.0, 4.0, 5.0, 6.0, 8.5]
4.2 Using numpy.divide()
- Convert the given list to a
Numpy
array usingnp.array
method. - Divide each element of this array with the given divisor using the
np.divide()
function. - To generate the resultant list from the output array you can use the
ndarray.tolist()
method.
Code:
import numpy as np li = [38, 57, 76, 95, 114, 161.5] arr = np.array(li) num = 19 res = np.divide(arr, num) print(res.tolist())
Output:
[2.0, 3.0, 4.0, 5.0, 6.0, 8.5]
๐A Quick Recap to numpy.divide()
The numpy.divide() method returns an element-wise true division of the inputs in the given array.
Syntax:
numpy.divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Here:
- x1 represents the Dividend array.
- x2 represents the Divisor array.
- The other parameters are optional. Read about them here.
โจWhen you have multiple division processes going on, you can accelerate it significantly by using NumPy division. Not only does it allow you to perform element-wise division but this also works on multi-dimensional NumPy arrays. For example:
import numpy as np # Create 2D lists a = [[1, 2, 3], [4, 5, 6]] b = [[2, 4, 6], [8, 10, 12]] # Convert lists to 2D NumPy arrays a = np.array(a) b = np.array(b) # Divide the 2D arrays print(a / b)
Output:
[[0.5 0.5 0.5]
[0.5 0.5 0.5]]
๐Related Article: The Ultimate Guide to NumPy
Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)
Conclusion
We have successfully learned four different ways of dividing elements in a given list with a given number. I hope this tutorial helped to answer all your queries. Please subscribe and stay tuned for more interesting tutorials. Happy learning! ๐
Web Scraping with BeautifulSoup
One of the most sought-after skills on Fiverr and Upwork is web scraping . Make no mistake: extracting data programmatically from web sites is a critical life-skill in todayโs world thatโs shaped by the web and remote work. This course teaches you the ins and outs of Pythonโs BeautifulSoup library for web scraping.