[Python] Why are multiple expressions and statements placed on one line in Python and not...

Discussão em 'Python' iniciado por Stack, Abril 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am coming from a Javascript background and am learning Python. I have been working on list exercises and saw this question and then then solution.


    Given a list of integers, replace every element with the greatest element among the elements to its right, and replace the last element with -1.

    Example:

    Input: [17, 18, 5, 4, 6, 1]
    Output: [18, 6, 6, 6, 1, -1]
    ​

    def greatest_on_right(lst):
    max_val = -1
    # we are starting at the end of the range and stepping down -1 and stopping when we get to -1 (past index 0)
    for i in range(len(lst) -1, -1, -1):
    # don't understand why these all have to be on the same line
    lst, max_val = max_val, max(max_val, lst)
    return lst


    Input list: [17, 17, 19, 5, 4, 6, 1]
    Output on one line: [19, 19, 6, 6, 6, 1, -1]
    Output on separate lines: [17, 17, 19, 5, 4, 6, 1]

    The comments are my understanding of how it works. When I tried placing the items below the for loop on individual lines, the return value was the original list. I have not been able to find mention of the style in the docs or PEP 8.

    Continue reading...

Compartilhe esta Página