Confusing Behaviour (list=[] in function)



  • On 12/09/2014 at 14:26, xxxxxxxx wrote:

    Hello everybody,

    I wrote the following lines and Im not able to understand what happens.

    import c4d  
    #Welcome to the world of Python  
      
    def A(lst=[]) :  
      lst.append("A")  
      return lst  
      
    def main() :  
      print A()
    

    If I execute the code first time the variable lst is printed in console exactly how I expect.

    >>>['A']
    

    If I execute second time...

    >>>['A']['A']
    

    third time...

    >>>['A']['A']['A']
    

    and so on.

    >>>['A']['A']['A']['A']  
    \>>>['A']['A']['A']['A']['A']  
    \>>>['A']['A']['A']['A']['A']['A']  
    \>>>['A']['A']['A']['A']['A']['A']['A']
    

    How can I stop that behaviour? 'del lst' didnt work.

    THX and Greeting
    rown



  • On 12/09/2014 at 17:08, xxxxxxxx wrote:

    This is because the argument to your function is only evaluated once when you first define the function. The default argument keeps getting used every time you call the function.

    One way to solve it is setting the default value of your argument to None and adjust the code block as necessary.



  • On 13/09/2014 at 03:57, xxxxxxxx wrote:

    Ok, thank you. Ive to think about. Didnt know that an argument isnt refreshed after calling second time.
    Solved that way

    import c4d  
    #Welcome to the world of Python  
      
    def A(lst=[]) :  
      l = lst[:]  
      l.append("A")  
      return l  
      
    def main() :  
      print A()
    


  • On 13/09/2014 at 04:09, xxxxxxxx wrote:

    why not just

    def A() :
        l = []
        l.append("A")
        return l
    

    or even

    def A() :
        return ["A"]
    


  • On 16/09/2014 at 05:00, xxxxxxxx wrote:

    Hi niklas,

    of course, you are right in this case. But I wanted to know how to handle lists as given argument.

    greetings
    rown


Log in to reply