python - How do I multiply each element in a list by a number? -
i have list:
my_list = [1, 2, 3, 4, 5]
how can multiply each element in my_list
5? output should be:
[5, 10, 15, 20, 25]
you can use list comprehension:
my_list = [1, 2, 3, 4, 5] my_new_list = [i * 5 in my_list] >>> print(my_new_list) [5, 10, 15, 20, 25]
note list comprehension more efficient way for
loop:
my_new_list = [] in my_list: my_new_list.append(i * 5) >>> print(my_new_list) [5, 10, 15, 20, 25]
as alternative, here solution using popular pandas package:
import pandas pd s = pd.series(my_list) >>> s * 5 0 5 1 10 2 15 3 20 4 25 dtype: int64
or, if want list:
>>> (s * 5).tolist() [5, 10, 15, 20, 25]
Comments
Post a Comment