Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python sum over map over list

From Mathematica I am used to summing over a map over a list with a very short and concise syntax. E.g. to sum a map over a polynomial function:

myList = {1,2,3};
output = Sum[ x^3+x^2+x , { x, myList } ]

To do the same thing in Python, I came up with the following syntax:

myList = [1,2,3]
output = sum(list(map(lambda x: x*x*x+x*x+x , myList)))

My question is: Is that the most simple/efficient way of doing this? I mean, it seems to me that there should be a simpler way than nesting three or four built in functions for such a simple task.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need the map or list, you can just sum using a generator expression

>>> myList = [1,2,3]
>>> sum(x**3 + x**2 + x for x in myList)
56
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading