Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] 
like image 369
bharath Avatar asked Nov 19 '11 15:11

bharath


People also ask

How do you multiply the elements of a list in Python by a number?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Can you multiply a list in Python?

Lists and strings have a lot in common. They are both sequences and, like pythons, they get longer as you feed them. Like a string, we can concatenate and multiply a Python list.

Can you multiply a list by a scalar in Python?

You can use any scalar types (int, float, Boolean, etc.) and any method other than traversal with the list multiplication function in python language. The first illustration was all about using a single list; however, we have used two lists in our second illustration.


2 Answers

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

like image 195
JoshAdel Avatar answered Sep 30 '22 18:09

JoshAdel


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] 
like image 33
KL-7 Avatar answered Sep 30 '22 16:09

KL-7