86

I am not able understand where does these type of functions are used and how differently these arguments work from the normal arguments. I have encountered them many time but never got chance to understand them properly.

Ex:

def method(self, *links, **locks):
    #some foo
    #some bar
    return

I know i could have search the documentation but i have no idea what to search for.

5
  • 3
    See a prev question: stackoverflow.com/questions/287085/… Commented Nov 29, 2010 at 18:05
  • 1
    Ditto--here is a link that will help: saltycrane.com/blog/2008/01/… Commented Mar 14, 2013 at 21:49
  • 13
    "I know i could have search the documentation but i have no idea what to search for." Happens all too often when learning. it would have been like saying "what's that thing in the stuff?" What some so-called "experts" forget is that sometimes tere's a minimum level of understanding require to know how the hell to ask a question. Commented Apr 10, 2014 at 20:24
  • 2
    You could be interested to read also one of the questions What does ** (double star) and * (star) do for Python parameters? or What does asterisk * mean in Python? Commented Sep 21, 2015 at 17:52
  • such a good question! Commented May 21, 2018 at 19:06

1 Answer 1

125

The *args and **keywordargs forms are used for passing lists of arguments and dictionaries of arguments, respectively. So if I had a function like this:

def printlist(*args):
    for x in args:
        print(x)

I could call it like this:

printlist(1, 2, 3, 4, 5)  # or as many more arguments as I'd like

For this

def printdict(**kwargs):
    print(repr(kwargs))

printdict(john=10, jill=12, david=15)

*args behaves like a list, and **keywordargs behaves like a dictionary, but you don't have to explicitly pass a list or a dict to the function.

See this for more examples.

Sign up to request clarification or add additional context in comments.

4 Comments

But can you explicitly pass a list or dict to the function?
Yes, you can. The list will be args[0] if you pass it "as is". In the other hand, f you call the function with an asterisk (not the one in the function definition, this is in the call) then, the passed list will BE THE actual args tuple.
*args is a tuple, not a list
>>> def d(*args): ... print(type(args)) >>> d(1, 2, 3) <type 'tuple'>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.