Search code examples
pythonfunctionargumentsmultiple-arguments

Variable number of arguments in function


Is it possible to run a function like this:

def call(a,*alphabets,*numbers):
    print(a)
    print(alphabets)
    print(numbers)

I'm getting the following error:

  File "<ipython-input-331-ddaef8a7e66f>", line 1
    def call(a,*alphabets,*numbers):
                          ^
SyntaxError: invalid syntax

Can somebody tell me if there's an alternative way to do this?


Solution

  • Quite simply: require the caller to pass two lists (or tuples or whatever):

    def call(a,alphabets=None,numbers=None):
        if alphabets is None:
            alphabets = []
        if numbers is None:
            numbers = []
        print(a)
        print(alphabets)
        print(numbers)
    
    
    call("?")
    call("?", ["a", "b", "c"])
    call("?", ["a", "b", "c"], (1, 2, 3))
    call("?"), None, (1, 2, 3))
    # etc