0

When using a list as a parameter in a recursive function, If I add items to that list using + operator everything works as expected. But if I am using the += operator the function return value changes. Why does it happens? aren't += has the same meaning as +?

def rec(str_bucket,s,temp=[]):
    if (''.join(temp))==s:
        return True
    if not str_bucket:
        return False
    
    **temp +=[str_bucket[0][0]]**     *# instead of: temp = temp+[str_bucket[0][0]]*
    a =rec(str_bucket[1:],s,temp)
    
    temp = temp[:-1]+[str_bucket[0][1]]
    b =rec(str_bucket[1:],s,temp)
    
    temp = temp[:-1]
    c = rec(str_bucket[1:],s,temp)
    
    return a or b or c 
  • 1
    `temp = temp+[str_bucket[0][0]]` creates new list `temp`, but `temp +=[str_bucket[0][0]]` only extends `temp` with new values. Note: Don't use `[]` as default value in parameters. – Andrej Kesely Oct 01 '20 at 12:08
  • 1
    The name `temp` refers to a local variable of function `rec`. If you change the value of this local variable by writing `temp = ...`, this has no effect on the value of the original list. However, if you write `temp += ...` or `temp.append(...)`, then you are modifying the list. – Stef Oct 01 '20 at 12:12
  • 1
    I also suggest you read [Least astonishment and the mutable default argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Stef Oct 01 '20 at 12:13
  • Welcome to SO! No, `+=` and `+` are different. Try `a = 3; a += 1; print(a)` versus `a = 3; a + 1; print(a)`. – ggorlen Oct 01 '20 at 19:37
  • Got it. Thanks to all of you ! – Iris Kanter Oct 11 '20 at 06:55

0 Answers0