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)
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 ndarray
import numpy as np a_list = [1, 2, 3] an_array = np.array(a_list) res = an_array * 2 print(res) print(type(res))
[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 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.