This question already has an answer here:
Hello so I want to multiply the integers inside a list.
For example;
l = [1, 2, 3]
l = [1*2, 2*2, 3*2]
output:
l = [2, 4, 6]
So I was searching online and most of the answers were regarding multiply all the integers with each other such as:
[1*2*3]
The most pythonic way would be to use a list comprehension:
If you need to do this for a large number of integers, use
numpy
arrays:A final alternative is to use map
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-parameteroperator.mul
with a fixed multipleusing numpy :
The simplest way to me is:
Try a list comprehension:
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 doto apply the function
lambda x: x * 2
to each element inl
. This is equivalent to: