How to divide all numbers in a list to a number?

All we need is an easy explanation of the problem, so here it is.

I have a list contains around 200 numbers. I need a list fraction of them. I mean I have a=[111,23,25,12,61]
I want b=[1/111,1/23,1/25,1/12,1/61]
How can i do that?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

With a list comprehension:

[1.0/x for x in a]

Method 2

You can use map to apply a function to every element of a list:

n = [111, 23, 25, 12, 61]
n_fractions = map(lambda x: 1/x, n)
# [0.009009009009009009, 0.043478260869565216, 0.04, 0.08333333333333333, 0.01639344262295082]

You can also use the built-in fractions.Fraction class to properly express the values as fractions:

n_fractions = list(map(lambda x: Fraction(1, x), n))
# [Fraction(1, 111), Fraction(1, 23), Fraction(1, 25), Fraction(1, 12), Fraction(1, 61)]

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

Leave a Reply