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.
This has probably been asked before, please read the language's docs at docs.python.org and consider using a simple "for i in range" loop where you can c += [a[i]] * b[i] in each iteration. A better duplicate target: Repeat each item in a list a number of times specified in another list.
The zip() function in python can combine the contents of 2 or more iterables. Zip Function returns a zipped output. We can then simply store the output in Result and Display it on the console. This is a very simple way to perform list multiplication in Python.
We will be deliberating the simplest and convenient way to multiply a list by a scalar in Python language. First, we create a list and add values to it. Our next step multiplies every item in the list by 3. Then we define a print function that prints the resultant values.
Try a list comprehension:
l = [x * 2 for x in l]
This goes through l
, multiplying each element by two.
Of course, there's more than one way to do it. If you're into lambda functions and map
, you can even do
l = map(lambda x: x * 2, l)
to apply the function lambda x: x * 2
to each element in l
. This is equivalent to:
def timesTwo(x):
return x * 2
l = map(timesTwo, l)
Note that map()
returns a map object, not a list, so if you really need a list afterwards you can use the list()
function afterwards, for instance:
l = list(map(timesTwo, l))
Thanks to Minyc510 in the comments for this clarification.
The most pythonic way would be to use a list comprehension:
l = [2*x for x in l]
If you need to do this for a large number of integers, use numpy
arrays:
l = numpy.array(l, dtype=int)*2
A final alternative is to use map
l = list(map(lambda x:2*x, l))
Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial
to utilize the two-parameter operator.mul
with a fixed multiple
>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
The simplest way to me is:
map((2).__mul__, [1, 2, 3])
using numpy :
In [1]: import numpy as np
In [2]: nums = np.array([1,2,3])*2
In [3]: nums.tolist()
Out[4]: [2, 4, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With