Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Turning a for-loop into a one-liner

I'm trying to create a matrix-multiplication-with-scalar function, without any libraries. It has to include list comprehension:

A = [[1,2],[3,4]] # 2by2 matrix

scalar = 2 #positive int

product = []

for row in A:
    
    temp = []
    
    for element in row:
        temp.append(scalar * element)
    
    product.append(temp)

print(product)
like image 721
7d2672d0f4 Avatar asked Aug 13 '26 13:08

7d2672d0f4


2 Answers

This is a possible solution:

A = [[1,2],[3,4]] # 2by2 matrix

scalar = 2 #positive int

product = [[i*scalar for i in sublist] for sublist in A]

print(product)
like image 101
lorenzozane Avatar answered Aug 16 '26 11:08

lorenzozane


Alternatively, you can have some fun with lambdas and map:

product = [*map(lambda x: [*map(lambda y: y * scalar, x)], A)]

Try it online!

like image 26
General Grievance Avatar answered Aug 16 '26 10:08

General Grievance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!