S
S
Sergey2020-07-08 14:04:09
Python
Sergey, 2020-07-08 14:04:09

Why such strange behavior of the variable after recursion?

Here everything was fine:

def test(mass):
    print("До рекурсии:",mass)
    
    if mass==1: return
    mass=mass-1
    test(mass)
    
    print("после рекурсии:",mass)
    
    
test(4)


But why is there such a mess?
def test(mass):
    print("До рекурсии:",mass)
    
    if len(mass)==1: return
    del mass[0]
    test(mass)
    
    print("после рекурсии:",mass)
    
    
test([4,3,2,1])


I've been fighting for a few hours now :-(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-07-08
@Shull

Because when passing a list as a parameter, it is not the list itself that is copied, but a link to it. When calling recursively, masspass mass.copy().

S
soremix, 2020-07-08
@SoreMix

You pass the same list, elements are removed from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question