Search code examples
pythonnewlinecode-readability

How to write long arithmetic expressions in several lines in python?


I have a long expression, its' not fitting in my screen, I want to write in several lines.

new_matrix[row][element] =  old_matrix[top_i][top_j]+old_matrix[index_i][element]+old_matrix[row][index_j]+old_matrix[row][index_j]

Python gives me 'indent' error if I just break line. Is there way to 'fit' long expression in screen?


Solution

  • I hate backslashes, so I prefer to enclose the right hand side in parens, and break/indent on the top-level operators:

    new_matrix[row][element] = (old_matrix[top_i][top_j]
                                + old_matrix[index_i][element]
                                + old_matrix[row][index_j]
                                + old_matrix[row][index_j])
    

    or (I think this is how black does it):

    new_matrix[row][element] = (
        old_matrix[top_i][top_j]
        + old_matrix[index_i][element]
        + old_matrix[row][index_j]
        + old_matrix[row][index_j]
    )