Skip to content Skip to sidebar Skip to footer

Python: Double For Loop In One Line

I have such a loop: for i in range(len(A)): for j in range(len(A[i])): A[i][j] = functionA(A[i][j]) Is this possible to write more compact in Python?

Solution 1:

You can use list comprehension.

Example code:

A = [[1,2,3],[4,5,6],[7,8,9]]
deffunctionA(a):
    return a+1

A = [[functionA(A[i][j]) for j inrange(len(A[i]))] for i inrange(len(A))]
print(A)

Result:

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Post a Comment for "Python: Double For Loop In One Line"