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

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?



Solution 1:[1]

With a list comprehension:

[1.0/x for x in a]

Solution 2:[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)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JulienD
Solution 2 MatsLindh