Open In App

Python - Constant Multiplication over List

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list we need to multiply each element in the list by a constant. For example, we are having a list a = [1, 2, 3, 4, 5] and constant c=2 we need to multiply this constant in whole list.

Using List Comprehension

List comprehension allows us to multiply each element in list by a constant by iterating through list and applying the multiplication. This results in a new list with modified values.

Python
a = [1, 2, 3, 4, 5]
c = 2

# Multiply each element in the list by the constant using list comprehension
res = [x * c for x in a]
print(res)

Output
[2, 4, 6, 8, 10]

Explanation:

  • List comprehension iterates through each element in list a and multiplies it by constant c.
  • Result is stored in the list res which contains elements of a after being multiplied by c.

Using map() with lambda

map() function applies the lambda function to each element in list multiplying each element by constant. The result is an iterator which is converted into a list for further use.

Python
a = [1, 2, 3, 4, 5]
c = 2

# Use map() with a lambda function to multiply each element by the constant
res = list(map(lambda x: x * c, a))
print(res)

Output
[2, 4, 6, 8, 10]

Explanation:

  • map() function applies lambda function (lambda x: x * c) to each element in list a, multiplying each element by constant c.
  • Result is an iterator which is converted into a list using list() storing the modified elements in res.

Using a for Loop

For loop iterates through each element in list a multiplying each element by constant c modified elements are then appended to list res.

Python
a = [1, 2, 3, 4, 5]
c = 2

# Multiply each element by the constant using a for loop
res = []
for x in a:
    res.append(x * c)
print(res)

Output
[2, 4, 6, 8, 10]

Explanation:

  • For loop iterates through each element in list a multiplying it by constant c (which is 2).
  • Result of each multiplication is appended to list res which stores modified values.

Using numpy

Using Numpy we can perform element-wise multiplication on entire array by multiplying Numpy array by constant. This allows for efficient and fast operations resulting in modified array.

Python
import numpy as np

a = [1, 2, 3, 4, 5]
c = 2

# Using numpy to multiply each element by the constant
n = np.array(a)
res = n * c
print(res)

Output
[ 2  4  6  8 10]

Explanation:

  • List a is converted into a NumPy array which allows for efficient element-wise operations.
  • Each element of array n is multiplied by constant c and result is stored in res.

Next Article
Practice Tags :

Similar Reads