Divide list by number python

I just want to divide each element in a list by an int.

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = myList/myInt

This is the error:

TypeError: unsupported operand type(s) for /: 'list' and 'int'

I understand why I am receiving this error. But I am frustrated that I can't find a solution.

Also tried:

newList = [ a/b for a, b in (myList,myInt)]

Error:

ValueError: too many values to unpack

Expected Result:

newList = [1,2,3,4,5,6,7,8,9]


EDIT:

The following code gives me my expected result:

newList = []
for x in myList:
    newList.append(x/myInt)

But is there an easier/faster way to do this?

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
  • Method 2: Using a List Comprehension
  • Method 3: Using map and lambda
  • Method 4: Using Numpy
  • Conclusion

Video Walkthrough

How to Divide Each Element in a List in Python

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 variable a represents each element in the given list while num 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.

Mastering the Python Map Function [+Video]

📌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 values x+y+z.

Let's Play Finxter - The Lambda Function in Python

📌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 using np.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 using np.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.)

Divide list by number python

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

Divide list by number python

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.

Divide list by number python

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

How do you divide a list by a number in Python?

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.

How do you split a list into N parts in Python?

array_split() to split a list into n parts. Call numpy. array_split(list, n) to return a list of n NumPy arrays each containing approximately the same number of elements from list . Use the for-loop syntax for array in list to iterate over each array in list .