Just use a list comprehension to Multiply each element of a list by a number in Python. list comprehension is generally a more efficient way to do a for-loop.
Example Multiply each element of a list by a number in Python
Simple example code Multiplying each element of a list by a specified number (5).
my_list = [1, 2, 3, 4, 5]
new_list = [i * 5 for i in my_list]
print(new_list)
Output:
Same thing with for loop
my_list = [1, 2, 3, 4, 5]
new_list = []
for i in my_list:
new_list.append(i * 5)
print(new_list)
Output: [5, 10, 15, 20, 25]
As an alternative way
Using the popular Pandas package:
import pandas as pd
my_list = [1, 2, 3, 4, 5]
s = pd.Series(my_list)
new_list = (s * 5).tolist()
print(new_list)
Use a NumPy array
import numpy as np
a_list = [1, 2, 3]
an_array = np.array(a_list)
res = an_array * 2
print(res)
print(type(res))
Output:
[2 4 6]
<class 'numpy.ndarray'>
Do comment if you have any doubts or suggestions on this Python list multiply code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.