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.

Shiv Deepak
  • 3,122
  • 5
  • 34
  • 49
  • 3
    See a prev question: http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean – pyfunc Nov 29 '10 at 18:05
  • 1
    Ditto--here is a link that will help: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ – user798719 Mar 14 '13 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. – monsto Apr 10 '14 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?](http://stackoverflow.com/q/36901/2062965) or [What does asterisk * mean in Python?](http://stackoverflow.com/q/400739/2062965) – strpeter Sep 21 '15 at 17:52
  • such a good question! – Nicolas S.Xu May 21 '18 at 19:06

1 Answers1

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.

0 _
  • 10,524
  • 11
  • 77
  • 109
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151