Search code examples
pythonlistfunctionnonetypedefault-arguments

Most Pythonic way to convert None to an empty list in case a default argument is not passed in a Function?


I want to write a general function that takes two input variables var1, var2 and returns the concatenation of both.

Each variable has the default value None, and can be either a single element or a list.

The expected output should be a list (even if both var1 and var2 are None, it should return an empty list []).

Below is my function:

def my_func(var1=None, var2=None):
    if not isinstance(var1, list):
        var1 = [var1]
    if not isinstance(var2, list):
        var2 = [var2]
    return var1 + var2 

When I only input one variable, I get the following:

>>> lst = my_func(var2=[1, 2, 3])
>>> print(lst)
[None, 1, 2, 3]

I want to get

[1, 2, 3]

Is there any way to convert None to [] in the function, without changing the default None values?


Solution

  • You can check first if var (1 and 2) are Not None

    def my_func(var1=None, var2=None):
        var1 = var1 if var1 is not None else []
        var2 = var2 if var2 is not None else []
        if not isinstance(var1, list):
            var1 = [var1]
        if not isinstance(var2, list):
            var2 = [var2]
    
        return var1 + var2
    

    This will cover many cases, such as :

    print(my_func(var2=[1, 2, 3]))
    print(my_func(var1=None,var2=[1, 2, 3]))
    print(my_func(var1=0,var2=[1, 2, 3]))
    print(my_func(var1=False,var2=[1, 2, 3]))
    print(my_func(var1='',var2=[1, 2, 3]))
    

    [1, 2, 3]                                                                                                                                                                                                                                       
    [1, 2, 3]                                                                                                                                                                                                                                       
    [0, 1, 2, 3]                                                                                                                                                                                                                                    
    [False, 1, 2, 3]                                                                                                                                                                                                                                
    ['', 1, 2, 3]