[Python] How do python list items change if they are involved in recursive loops?

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    This function reverses all the items found in the list. Even the inner lists get reversed. My problem is that I do not understand how the reversed_list keeps 7 and 6 after the recursion. Since once the deep_reverse is called, the reversed_list becomes empty and then it keeps the reverse of the inner list which is [5, 4, 3]. What I do not realize is that once this item is appended the reversed_list becomes [7, 6, [5, 4, 3]]

    def deep_reverse(arr):

    # Terminaiton / Base condition
    if len(arr) < 1:
    return arr

    reversed_items = [] # final list to be returned
    for item in arr[::-1]:

    # If this item is a list itself, invoke deep_reverse to reverse the items recursively.
    if type(item) is list:
    item = deep_reverse(item)

    # append the item to the final list
    reversed_items.append(item)
    print(reversed_items)

    return reversed_items ```

    deep_reverse([1, 2, [3, 4, 5], 6, 7])
    #printing the reversed_list
    [7]
    [7, 6]
    [5]
    [5, 4]
    [5, 4, 3]
    [7, 6, [5, 4, 3]]
    [7, 6, [5, 4, 3], 2]
    [7, 6, [5, 4, 3], 2, 1]

    Continue reading...

Compartilhe esta Página