Doing math to a list in python

If you're going to be doing lots of array operations, then you will probably find it useful to install Numpy. Then you can use ordinary arithmetic operations element-wise on arrays, and there are lots of useful functions for computing with arrays.

>>> import numpy
>>> a = numpy.array([111,222,333])
>>> a * 3
array([333, 666, 999])
>>> a + 7
array([118, 229, 340])
>>> numpy.dot(a, a)
172494
>>> numpy.mean(a), numpy.std(a)
(222.0, 90.631120482977593)

[3*x for x in [111, 222, 333]]

As an alternative you can use the map command as in the following:

map(lambda x: 3*x, [111, 222, 333])

Pretty handy if you have a more complex function to apply to a sequence.

Tags:

Python

List