Skip to content

How to Multiply a List by a Scalar in Python

If you need to multiply a list by a scalar in Python, then you can do one of the following:

Option 1 – Using List Comprehensions

li = [1,2,3,4] multiple = 2.5 li = [x*multiple for x in li] print(li)
Code language: Python (python)

Output: [2.5, 5.0, 7.5, 10.0]

Option 2 – Using map()

li = [1,2,3,4] multiple = 2.5 def multiply(le): return le*multiple li = list(map(multiply,li)) print(li)
Code language: Python (python)

Output: [2.5, 5.0, 7.5, 10.0]

Option 3 – Using Lambda Functions

li = [1,2,3,4] multiple = 2.5 li = list(map(lambda x: x*multiple, li)) print(li)
Code language: Python (python)

Output: [2.5, 5.0, 7.5, 10.0]

Option 4 – Using Numpy Arrays

import numpy as np li = [1,2,3,4] multiple = 2.5 arr = np.array(li) arr = arr * multiple li = arr.tolist() print(li)
Code language: Python (python)

Output: [2.5, 5.0, 7.5, 10.0]

See also  How to Get the Number of Lines in a File in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x