2

Python newb here. Suppose you have a function like

def myfunc(a = "apple", *args):
    print(a)
    for b in args:
        print(b + "!")

How do you pass a set of unnamed arguments to *args without altering the default argument?

What I want to do is

myfunc(,"banana", "orange")

and get the output

apple
banana!
orange!

but this doesn't work.

(I'm sure this has been discussed before but all my searching came up empty)

1 Answer 1

2

In Python 3 you can do this by changing a to a keyword only argument:

>>> def myfunc(*args, a="apple"):
        print(a)
        for b in args:
            print(b + "!")
...         
>>> myfunc("banana", "orange")
apple
banana!
orange!
>>> myfunc("banana", "orange", a="watermelon")
watermelon
banana!
orange!

In Python 2 you'll have to do something like this:

>>> def myfunc(*args, **kwargs):
        a = kwargs.pop('a', 'apple')
        print a 
        for b in args:
             print b + "!"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.