Python – Constant Multiplication over List
While working with the python lists, we can come over a situation in which we require to multiply constant to each element in the list. We possibly need to iterate and multiply constant to each element but that would increase the line of code. Let’s discuss certain shorthands to perform this task.
Method #1 : Using List Comprehension
List comprehension is just the short way to perform the task we perform using the naive method. This is mainly useful to save time and also is best among others when it comes to the readability of the code.
Python3
# Python3 code to demonstrate # Constant Multiplication over List # using list comprehension # initializing list test_list = [ 4 , 5 , 6 , 3 , 9 ] # printing original list print ( "The original list is : " + str (test_list)) # initializing K K = 4 # using list comprehension # Constant Multiplication over List res = [x * K for x in test_list] # printing result print ( "The list after constant multiplication : " + str (res)) |
The original list is : [4, 5, 6, 3, 9] The list after constant multiplication : [16, 20, 24, 12, 36]
Time Complexity: O(n), The above code iterates through the list once, hence the time complexity is linear, i.e. O(n).
Auxiliary Space: O(n), The algorithm uses an additional list to store the result, thus consuming linear space which is O(n).
Method #2 : Using map() + operator.mul
This is similar to the above function but uses the operator.mul to multiply each element to other element from the other list of K formed before applying the map function. It multiplies the similar index elements of list.
Python3
# Python3 code to demonstrate # Constant Multiplication over List # using map() + operator.mul import operator # initializing list test_list = [ 4 , 5 , 6 , 3 , 9 ] # printing original list print ( "The original list is : " + str (test_list)) # initializing K list K_list = [ 4 ] * len (test_list) # using map() + operator.mul # Constant Multiplication over List res = list ( map (operator.mul, test_list, K_list)) # printing result print ( "The list after constant multiplication : " + str (res)) |
The original list is : [4, 5, 6, 3, 9] The list after constant multiplication : [16, 20, 24, 12, 36]
Method #3 : Using numpy
Note: Install numpy module using command “pip install numpy”
Another approach to perform constant multiplication over a list is by using numpy library.
Python3
import numpy as np # Python program to perform constant multiplication over a list test_list = [ 4 , 5 , 6 , 3 , 9 ] K = 4 # Using numpy result = list (np.array(test_list) * K) # printing result print ( "The list after constant multiplication :" , result) #This code is contributed by Edula Vinay Kumar Reddy |
Output:
The list after constant multiplication : [16, 20, 24, 12, 36]
Time complexity: O(n) as it is iterating through the list once.
Auxiliary Space: O(n) as it is creating a new list with multiplied values.
Please Login to comment...