Search code examples
pythonlistfunctionparametersdefault

Elegant way for passing list to function as input arguments with incomplete list/missing list entries


I'm writing a program (see below) where the user can set parameters x[0] and x[1]. Sometimes the user is not setting x[1] as it's not always needed (tested with #x[1]=2). If x[1] is not set, I want the function to use the default b=5 as value. When testing, as expected, when function1 is called, it gives me an error saying x[1] is missing. I tried a lot playing aroung with "=None" etc, but can't get it to recognize x[1] is non-existing and using b=5 as default.

Anyone knows a elegant pythonian way to implement this? (I guess there's a simple way that slipped my tired mind or I, as beginner, simply don'T know up to now :)

Thx, Toby

def function1(a, b=5):
    print(a)
    print(b)

x={}
x[0]=1
#x[1]=2

function1(x[0],x[1])

Solution

  • Your function definition can stay the same:

    def function1(a, b=5):
        print(a)
        print(b)
    

    Your way of calling the function needs to change.

    For positional arguments don't use a dict {}, use a list []:

    x = [1, 2]
    function1(*x)     # prints 1 & 2
    
    x = [1]
    function1(*x)     # prints 1 & 5
    

    For named arguments use a dict (but then you have to call the values a and b, like the function does):

    x = {"a": 1, "b": 2}
    function1(**x)     # prints 1 & 2
    
    x = {"a": 1}
    function1(**x)     # prints 1 & 5
    

    When used in a function call, the * operator unpacks lists, and the ** operators unpacks dicts into the function's arguments.