Search code examples
pythonkeyword-argument

How do I implicitly define a parameter to an empty list?


In the code below, I've been wondering how we could tell if a parameter, b, is given.

The problem is that the third call of func does not retain [5] in a newly created list but rather some pointer in the start that b is pointing to. I'm guessing this is defined before in the program stack entering func call itself, so the calling and returning of func would not change b...?

Any insight is appreciated.

def func(a, b=[]):

    b.append([a])
    print(b)
    return b

func(3)
func(4, [])
func(5)

Solution

  • The best way is to assign the default value of b to something arbitrary (usually None) then check if b is defined that way:

    def func(a, b=None):
        if b is None:
            b = []
    
        b.append([a])
        print(b)
        return b
    
    func(3)
    func(4, [])
    func(5)