Multiply each element of a list by a number in Python
In this post, you will learn how to multiply each element of a list by a number in Python Programming.
Using forloop
Suppose we have given a list, and we want to multiply each element of the list by number 2. In the given example, we use the for loop and multiply each element of the list with the given number.
# Python program to multiply
# each element of a list by a number
x_list = [4, 5, 7, 32, 23, 12, 10]
multiplied_list = [ele * 2 for ele in x_list]
print(multiplied_list)
Output of the above code
[8, 10, 14, 64, 46, 24, 20]
Using lambda function
A lambda function is a small anonymous function which takes any number of arguments, but can only have one expression. In the given example, we asked the user to enter a number to be multiplied by the element of the given list.
# Python program to multiply
# each element of a list by a number
num=int(input('Please enter a number: '))
a_list = [3, 4, 1, 34, 21, 5]
a_list = list(map(lambda x:x*num,a_list))
print(a_list)
Output of the above code
Please enter a number: 4
[12, 16, 4, 136, 84, 20]
Using a numpy ndarray
In the given example, we use the numpy.array(object) with object as a list to convert object to a NumPy array. Next, we multiply each element of the array with the given number.
import numpy as np
x_list = [2, 8, 3, 12, 19, 21, 20]
an_array = np.array(x_list)
multiplied_list = an_array * 2
print(multiplied_list)
Output of the above code
[ 4 16 6 24 38 42 40]
Related Articles
Convert binary to decimal in Python
Trigonometric functions Python Numpy
Python convert list to numpy array
Python Numpy Array Shape
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Multiply all elements in list Python
Python Pandas Dataframe to CSV
Python Pandas DataFrame
Convert list to dictionary Python
Python dict inside list
Convert dictionary to dataframe Python
Python Pandas CSV to Dataframe
Convert List to Dataframe Python
Python add list to list
Difference between tuple and list in Python
Convert Excel to CSV Python Pandas
Alphabetical order Python
Python | Generate QR Code using pyqrcode module