How to multiply individual elements of a list with a number?

PythonNumpyMultiplication

Python Problem Overview


S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45

Here S is an array

How will I multiply this and get the value?

SP = [53.9, 80.85, 111.72, 52.92, 126.91]

Python Solutions


Solution 1 - Python

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Solution 2 - Python

You can use built-in map function:

result = map(lambda x: x * P, S)

or list comprehensions that is a bit more pythonic:

result = [x * P for x in S]

Solution 3 - Python

If you use numpy.multiply

S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
multiply(S, P)

It gives you as a result

array([53.9 , 80.85, 111.72, 52.92, 126.91])

Solution 4 - Python

Here is a functional approach using map, itertools.repeat and operator.mul:

import operator
from itertools import repeat


def scalar_multiplication(vector, scalar):
    yield from map(operator.mul, vector, repeat(scalar))

Example of usage:

>>> v = [1, 2, 3, 4]
>>> c = 3
>>> list(scalar_multiplication(v, c))
[3, 6, 9, 12]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbharathView Question on Stackoverflow
Solution 1 - PythonJoshAdelView Answer on Stackoverflow
Solution 2 - PythonKL-7View Answer on Stackoverflow
Solution 3 - PythonDKKView Answer on Stackoverflow
Solution 4 - PythonGeorgyView Answer on Stackoverflow