Sharanya Arcot Desai
Sharanya Arcot Desai

Reputation: 685

multiply every item in a 2D list by a scalar in python

m is a 2D matrix, something like:

[[1,2,3],[3,4,5],[6,7,1]]

print([i*5 for i in [j for j in m]]) does not work. It repeats items in each row 5 items. I'd like every item to be multiplies by the scalar 5.

Don't want to use numpy. How do I solve this using list comprehensions? Thank you!

Upvotes: 2

Views: 8249

Answers (4)

Daniel Crompton
Daniel Crompton

Reputation: 496

multiply every item in a 2D list by a scalar in python

Installation: python3 -m pip install numpy

numpy_array = np.array(L)
scale_factor = 2
result = numpy_array * scale_factor

Upvotes: 0

iGian
iGian

Reputation: 11193

I see you require list comprehension, but just to show the option with numpy:

import numpy as np

v = [[1,2,3],[3,4,5],[6,7,1]]
vv = np.array(v)

print(vv*5)
# [[ 5 10 15]
#  [15 20 25]
#  [30 35  5]]

Upvotes: 2

gilch
gilch

Reputation: 11651

Python lists are always one-dimensional. Your "matrix" is just a list of three lists, not a 2D list. Thus, your outer list comprehension needs to generate lists as its elements.

[[i*5 for i in row] for row in m]

It helps to think of list comprehensions as for loops with accumulators, i.e.

output = []
for row in m:
    output.append([i*5 for i in row])

Upvotes: 1

sam46
sam46

Reputation: 1271

a = [[1,2,3],[3,4,5],[6,7,1]]
print([[j*5 for j in i] for i in a])

output:

[[5, 10, 15], [15, 20, 25], [30, 35, 5]]

Upvotes: 2

Related Questions