HomeSoftware EngineeringLearn how to Multiply a Listing by a Scalar in Python

Learn how to Multiply a Listing by a Scalar in Python


If you must multiply an inventory by a scalar in Python, then you are able to do one of many following:

Possibility 1 – Utilizing Listing Comprehensions

li = [1,2,3,4]
a number of = 2.5
li = [x*multiple for x in li]
print(li)

Output: [2.5, 5.0, 7.5, 10.0]

Possibility 2 – Utilizing map()

li = [1,2,3,4]
a number of = 2.5
def multiply(le):
    return le*a number of

li = checklist(map(multiply,li))
print(li)

Output: [2.5, 5.0, 7.5, 10.0]

Possibility 3 – Utilizing Lambda Features

li = [1,2,3,4]
a number of = 2.5
li = checklist(map(lambda x: x*a number of, li))
print(li)

Output: [2.5, 5.0, 7.5, 10.0]

Possibility 4 – Utilizing Numpy Arrays

import numpy as np
li = [1,2,3,4]
a number of = 2.5
arr = np.array(li)
arr = arr * a number of
li = arr.tolist()
print(li)

Output: [2.5, 5.0, 7.5, 10.0]

RELATED ARTICLES

Most Popular

Recent Comments