Sunday, 3 September 2017

Python Q & A

What You Wrote

def append_to(element, to=[]):
    to.append(element)
    return to

What You Might Have Expected to Happen

my_list = append_to(12)
print my_list  

my_other_list = append_to(42)
print my_other_list
A new list is created each time the function is called if a second argument isn’t provided, so that the output is:
[12]
[42]

What You Should Do Instead

Create a new object each time the function is called, by using a default arg to signal that no argument was provided (None is often a good choice).
def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to
[12]
[12, 42] 

No comments:

Post a Comment