Doing math to a list in python

Viewed 92589

How do I, say, take [111, 222, 333] and multiply it by 3 to get [333, 666, 999]?

5 Answers

An alternative with the use of a map:

def multiply(a):
   return a * 3

s = list(map(multiply,[111,222,333]))

Here is a handy set of functions to perform several basic operations on lists. It uses the 'Listoper' class from the listfun module that can be installed through pip. The appropriate function for your case would be: "listscale(a,b): Returns list of the product of scalar "a" with list "b" if "a" is scalar, or other way around" Code:

!pip install listfun
from listfun import Listoper as lst
x=lst.listscale(3,[111,222,333])
print(x)

Output:

[333, 666, 999]

Of course if it is just a one time operation you could just do a list comprehension as suggested by others, but if you need to perform several list operations, then the listfun might help.

Hope this helps

Link to the PypI: https://pypi.org/project/listfun/1.0/ Documentation with example code can be found in the Readme file at: https://github.com/kgraghav/Listfun

Related