How to Multiply Each Element in a List by a Number

How do I multiply each element in a list by a number?

You can just use a list comprehension:

my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]

>>> print(my_new_list)
[5, 10, 15, 20, 25]

Note that a list comprehension is generally a more efficient way to do a for loop:

my_new_list = []
for i in my_list:
my_new_list.append(i * 5)

>>> print(my_new_list)
[5, 10, 15, 20, 25]

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd

s = pd.Series(my_list)

>>> s * 5
0 5
1 10
2 15
3 20
4 25
dtype: int64

Or, if you just want the list:

>>> (s * 5).tolist()
[5, 10, 15, 20, 25]

Finally, one could use map, although this is generally frowned upon.

my_new_list = map(lambda x: x * 5, my_list)

Using map, however, is generally less efficient. Per a comment from ShadowRanger on a deleted answer to this question:

The reason "no one" uses it is that, in general, it's a performance
pessimization. The only time it's worth considering map in CPython is
if you're using a built-in function implemented in C as the mapping
function; otherwise, map is going to run equal to or slower than the
more Pythonic listcomp or genexpr (which are also more explicit about
whether they're lazy generators or eager list creators; on Py3, your
code wouldn't work without wrapping the map call in list). If you're
using map with a lambda function, stop, you're doing it wrong.

And another one of his comments posted to this reply:

Please don't teach people to use map with lambda; the instant you
need a lambda, you'd have been better off with a list comprehension
or generator expression. If you're clever, you can make map work
without lambdas a lot, e.g. in this case, map((5).__mul__, my_list), although in this particular case, thanks to some
optimizations in the byte code interpreter for simple int math, [x * 5 for x in my_list] is faster, as well as being more Pythonic and simpler.

How to multiply each elements in a list in Python

You are multiplying strings. Instead multiply integers.

list = ['123', '456', '789']
my_new_list = []
for i in list:
my_new_list.append(int(i)*2)

print (my_new_list)

Or just make every number in list an integer.
Also here is a list comprehension version of your code

list = ['123', '456', '789']
my_new_list = [int(i)*2 for i in list]

List Comprehension you should look into it. What does "list comprehension" mean? How does it work and how can I use it?

Multiply a list by the elements of other list

Try this:

factors = [1, 2, 3]
values = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

multiply = []
for idx, lst in enumerate(values):
multiply.append([factors[idx] * x for x in lst])

print(multiply)

For a list comprehension version of the above code, see @Hommes answer

How do I multiply each element in a list of list by a number?

Using list comprehensions:

def multiply_2D_list(l, by=2):
return [[i * by for i in sub_list] for sub_list in l]

my_list = [[1, 2, 3],[ 4, 5, 6],[7, 8, 9]]
print(multiply_2D_list(my_list))

Using numpy

import numpy as np
my_list = [[1, 2, 3],[ 4, 5, 6],[7, 8, 9]]
print((np.array(my_list) * 2).tolist())

Using numpy requires sublists to have the same number of elements though

Multiply each element of a list by an entire other list

You can do this using matrix multiplication, and then flattening the result.

>>> a = np.array([1,0]).reshape(-1,1)
>>> b = np.array([1,0,1,0])
>>> a*b
array([[1, 0, 1, 0],
[0, 0, 0, 0]])
>>> (a*b).flatten()
array([1, 0, 1, 0, 0, 0, 0, 0])
>>>

How to multiply all integers inside list

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.

Multiply two lists but multiply each number in the first list by all numbers in the second list in python

numpy

a = np.array([1,2])
b = np.array([1,2,3])

c = (a[:,None]*b).sum(1)

output: array([ 6, 12])

python

a = [1,2]
b = [1,2,3]

c = [sum(x*y for y in b) for x in a]

output: [6, 12]



old answer (product per element)

numpy
a = np.array([1,2])
b = np.array([1,2,3])
c = (a[:,None]*b).ravel()

output: array([1, 2, 3, 2, 4, 6])

python
a = [1,2]
b = [1,2,3]

c = [x*y for x in a for y in b]

## OR
from itertools import product
c = [x*y for x,y in product(a,b)]

output: [1, 2, 3, 2, 4, 6]



Related Topics



Leave a reply



Submit