7d2672d0f4
7d2672d0f4

Reputation: 33

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)

Upvotes: 3

Views: 57

Answers (2)

General Grievance
General Grievance

Reputation: 4988

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

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

Try it online!

Upvotes: 1

lorenzozane
lorenzozane

Reputation: 1279

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)

Upvotes: 1

Related Questions