31

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


See also: How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)? . However, some techniques - especially ones involving Numpy - are specific to "doing math".

1

5 Answers 5

41
[3*x for x in [111, 222, 333]]
Sign up to request clarification or add additional context in comments.

Comments

25

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)

Comments

4

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.

2 Comments

This just returns a <map object at...> some memory pointer, how do you actually get the data from it?
@george this probably doesn't apply anymore, but if it helps anyone else: map and list are two different datatypes (I think this became explicitly the case in python 3.x) to turn a map into a list, simply use the list() function. So the example above would become list(map(lambda x: 3*x, [111, 222, 333]))
1

An alternative with the use of a map:

def multiply(a):
   return a * 3

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

Comments

1

Here is a handy set of functions (from me) 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

1 Comment

The usernames aren't an exact match, but I assume this package is your own work? If so, you should be explicit about this - see our self-promotion policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.