[Python] Python recursion prints all elements repeatedly instead of printing each elements on...

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a recursive function that prints all the elements from the list but the output is not what I expected. It first prints the numbers infinity (1)... and then crashes.

    So what am I doing wrong here?

    Here is my code

    I tried returning the print_list with lst[0:] and it prints

    def print_list(lst):
    if not lst:
    return 0
    else:
    print(lst[0])
    return print_list(lst[0:])


    print_list([1,2,3,4,5])


    output:

    Traceback (most recent call last):
    File "C:\Users\Lenovo\PycharmProjects\pyprac\Main.py", line 9, in <module>
    print_list([1,2,3,4,5])
    File "C:\Users\Lenovo\PycharmProjects\pyprac\Main.py", line 6, in print_list
    return print_list(lst[0:])
    ^^^^^^^^^^^^^^^^^^^
    File "C:\Users\Lenovo\PycharmProjects\pyprac\Main.py", line 6, in print_list
    return print_list(lst[0:])
    ^^^^^^^^^^^^^^^^^^^
    File "C:\Users\Lenovo\PycharmProjects\pyprac\Main.py", line 6, in print_list
    return print_list(lst[0:])
    ^^^^^^^^^^^^^^^^^^^
    [Previous line repeated 994 more times]
    File "C:\Users\Lenovo\PycharmProjects\pyprac\Main.py", line 5, in print_list
    print(lst[0])
    RecursionError: maximum recursion depth exceeded while calling a Python object
    1
    1
    1
    1
    1
    1
    1
    1
    1
    1
    1
    1
    1
    ...



    My expected output:

    1
    2
    3
    4
    5


    Any help will be appreciated!

    Continue reading...

Compartilhe esta Página