'How can i use for loop in lambda or any one line function?

I have a task to transform this code to one line and I really dont know how to do it. I couldnt find anything that solve this problem.

Here's the code:

def rowsub(mat, row1, row2, factor):
   for i in range(len(mat[row2])):
      mat[row2][i] -= factor * mat[row1][i]

I know its not helps in any way to do it a one line but thats my task. If someone can help I would be glad

Im using python 3.7



Solution 1:[1]

Instead of using i in range(i in len(mat[row2])) you can just use i,num in enumerate(mat[row2]) to get the index value of the number to i and the value of the number to num.

def rowsub(mat, row1, row2, factor):
    mat[row2]=[ num-factor*(mat[row1][i]) for i,num in enumerate(mat[row2])]

To write this oneliner I used generator expressions in which you can create a list of values in a single line.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rewerter Retrewer