<p>What do <code>*args</code> and <code>**kwargs</code> mean?</p>
<pre><code>def foo(x, y, *args):
def bar(x, y, **kwargs):
</code></pre>

[{'answer_id': 36902, 'author': 'Chris Upchurch', 'author_id': 2600, 'author_profile': 'https://Stackoverflow.com/users/2600', 'pm_score': 4, 'selected': False, 'text': '<p>From the Python documentation:</p>\n\n<blockquote>\n  <p>If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments). </p>\n  \n  <p>If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments. </p>\n</blockquote>\n'}, {'answer_id': 36908, 'author': 'Peter Hoffmann', 'author_id': 720, 'author_profile': 'https://Stackoverflow.com/users/720', 'pm_score': 13, 'selected': True, 'text': '<p>The <code>*args</code> and <code>**kwargs</code> is a common idiom to allow arbitrary number of arguments to functions as described in the section <a href="http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions" rel="noreferrer">more on defining functions</a> in the Python documentation.</p>\n<p>The <code>*args</code> will give you all function parameters <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="noreferrer">as a tuple</a>:</p>\n<pre><code>def foo(*args):\n    for a in args:\n        print(a)        \n\nfoo(1)\n# 1\n\nfoo(1,2,3)\n# 1\n# 2\n# 3\n</code></pre>\n<p>The <code>**kwargs</code> will give you all\n<strong>keyword arguments</strong> except for those corresponding to a formal parameter as a dictionary.</p>\n<pre><code>def bar(**kwargs):\n    for a in kwargs:\n        print(a, kwargs[a])  \n\nbar(name=\'one\', age=27)\n# name one\n# age 27\n</code></pre>\n<p>Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:</p>\n<pre><code>def foo(kind, *args, **kwargs):\n   pass\n</code></pre>\n<p>It is also possible to use this the other way around:</p>\n<pre><code>def foo(a, b, c):\n    print(a, b, c)\n\nobj = {\'b\':10, \'c\':\'lee\'}\n\nfoo(100,**obj)\n# 100 10 lee\n</code></pre>\n<p>Another usage of the <code>*l</code> idiom is to <strong>unpack argument lists</strong> when calling a function.</p>\n<pre><code>def foo(bar, lee):\n    print(bar, lee)\n\nl = [1,2]\n\nfoo(*l)\n# 1 2\n</code></pre>\n<p>In Python 3 it is possible to use <code>*l</code> on the left side of an assignment (<a href="http://www.python.org/dev/peps/pep-3132/" rel="noreferrer">Extended Iterable Unpacking</a>), though it gives a list instead of a tuple in this context:</p>\n<pre><code>first, *rest = [1,2,3,4]\nfirst, *l, last = [1,2,3,4]\n</code></pre>\n<p>Also Python 3 adds new semantic (refer <a href="https://www.python.org/dev/peps/pep-3102/" rel="noreferrer">PEP 3102</a>):</p>\n<pre><code>def func(arg1, arg2, arg3, *, kwarg1, kwarg2):\n    pass\n</code></pre>\n<p>For example the following works in python 3 but not python 2:</p>\n<pre><code>&gt;&gt;&gt; x = [1, 2]\n&gt;&gt;&gt; [*x]\n[1, 2]\n&gt;&gt;&gt; [*x, 3, 4]\n[1, 2, 3, 4]\n\n&gt;&gt;&gt; x = {1:1, 2:2}\n&gt;&gt;&gt; x\n{1: 1, 2: 2}\n&gt;&gt;&gt; {**x, 3:3, 4:4}\n{1: 1, 2: 2, 3: 3, 4: 4}\n</code></pre>\n<p>Such function accepts only 3 positional arguments, and everything after <code>*</code> can only be passed as keyword arguments.</p>\n<h3>Note:</h3>\n<ul>\n<li>A Python <code>dict</code>, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.</li>\n<li>&quot;The order of elements in <code>**kwargs</code> now corresponds to the order in which keyword arguments were passed to the function.&quot; - <a href="https://docs.python.org/3/whatsnew/3.6.html" rel="noreferrer">What’s New In Python 3.6</a></li>\n<li>In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.</li>\n</ul>\n'}, {'answer_id': 36911, 'author': 'nickd', 'author_id': 2373, 'author_profile': 'https://Stackoverflow.com/users/2373', 'pm_score': 8, 'selected': False, 'text': "<p>The single * means that there can be any number of extra positional arguments. <code>foo()</code> can be invoked like <code>foo(1,2,3,4,5)</code>. In the body of foo() param2 is a sequence containing 2-5.</p>\n\n<p>The double ** means there can be any number of extra named parameters. <code>bar()</code> can be invoked like <code>bar(1, a=2, b=3)</code>. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }</p>\n\n<p>With the following code:</p>\n\n<pre><code>def foo(param1, *param2):\n    print(param1)\n    print(param2)\n\ndef bar(param1, **param2):\n    print(param1)\n    print(param2)\n\nfoo(1,2,3,4,5)\nbar(1,a=2,b=3)\n</code></pre>\n\n<p>the output is</p>\n\n<pre><code>1\n(2, 3, 4, 5)\n1\n{'a': 2, 'b': 3}\n</code></pre>\n"}, {'answer_id': 36926, 'author': 'Lorin Hochstein', 'author_id': 742, 'author_profile': 'https://Stackoverflow.com/users/742', 'pm_score': 10, 'selected': False, 'text': '<p>It\'s also worth noting that you can use <code>*</code> and <code>**</code> when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:</p>\n\n<pre><code>def foo(x,y,z):\n    print("x=" + str(x))\n    print("y=" + str(y))\n    print("z=" + str(z))\n</code></pre>\n\n<p>You can do things like:</p>\n\n<pre><code>&gt;&gt;&gt; mylist = [1,2,3]\n&gt;&gt;&gt; foo(*mylist)\nx=1\ny=2\nz=3\n\n&gt;&gt;&gt; mydict = {\'x\':1,\'y\':2,\'z\':3}\n&gt;&gt;&gt; foo(**mydict)\nx=1\ny=2\nz=3\n\n&gt;&gt;&gt; mytuple = (1, 2, 3)\n&gt;&gt;&gt; foo(*mytuple)\nx=1\ny=2\nz=3\n</code></pre>\n\n<p>Note: The keys in <code>mydict</code> have to be named exactly like the parameters of function <code>foo</code>. Otherwise it will throw a <code>TypeError</code>:</p>\n\n<pre><code>&gt;&gt;&gt; mydict = {\'x\':1,\'y\':2,\'z\':3,\'badnews\':9}\n&gt;&gt;&gt; foo(**mydict)\nTraceback (most recent call last):\n  File "&lt;stdin&gt;", line 1, in &lt;module&gt;\nTypeError: foo() got an unexpected keyword argument \'badnews\'\n</code></pre>\n'}, {'answer_id': 12362812, 'author': 'ronak', 'author_id': 1327247, 'author_profile': 'https://Stackoverflow.com/users/1327247', 'pm_score': 5, 'selected': False, 'text': '<p><code>*</code> and <code>**</code> have special usage in the function argument list. <code>*</code>\nimplies that the argument is a list and <code>**</code> implies that the argument\nis a dictionary. This allows functions to take arbitrary number of\narguments</p>\n'}, {'answer_id': 26365795, 'author': 'Russia Must Remove Putin', 'author_id': 541136, 'author_profile': 'https://Stackoverflow.com/users/541136', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n<h1>What does <code>**</code> (double star) and <code>*</code> (star) do for parameters?</h1>\n</blockquote>\n<p>They allow for <strong>functions to be defined to accept</strong> and for <strong>users to pass</strong> any number of arguments, positional (<code>*</code>) and keyword (<code>**</code>).</p>\n<h2>Defining Functions</h2>\n<p><code>*args</code> allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named <code>args</code>.</p>\n<p><code>**kwargs</code> allows for any number of optional keyword arguments (parameters), which will be in a dict named <code>kwargs</code>.</p>\n<p>You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, <code>args</code> and <code>kwargs</code> are standard names.</p>\n<h2>Expansion, Passing any number of arguments</h2>\n<p>You can also use <code>*args</code> and <code>**kwargs</code> to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.</p>\n<p>The function recieving the parameters does not have to know that they are being expanded.</p>\n<p>For example, Python 2\'s xrange does not explicitly expect <code>*args</code>, but since it takes 3 integers as arguments:</p>\n<pre><code>&gt;&gt;&gt; x = xrange(3) # create our *args - an iterable of 3 integers\n&gt;&gt;&gt; xrange(*x)    # expand here\nxrange(0, 2, 2)\n</code></pre>\n<p>As another example, we can use dict expansion in <code>str.format</code>:</p>\n<pre><code>&gt;&gt;&gt; foo = \'FOO\'\n&gt;&gt;&gt; bar = \'BAR\'\n&gt;&gt;&gt; \'this is foo, {foo} and bar, {bar}\'.format(**locals())\n\'this is foo, FOO and bar, BAR\'\n</code></pre>\n<h2>New in Python 3: Defining functions with keyword only arguments</h2>\n<p>You can have <a href="https://www.python.org/dev/peps/pep-3102/" rel="noreferrer">keyword only arguments</a> after the <code>*args</code> - for example, here, <code>kwarg2</code> must be given as a keyword argument - not positionally:</p>\n<pre><code>def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs): \n    return arg, kwarg, args, kwarg2, kwargs\n</code></pre>\n<p>Usage:</p>\n<pre><code>&gt;&gt;&gt; foo(1,2,3,4,5,kwarg2=\'kwarg2\', bar=\'bar\', baz=\'baz\')\n(1, 2, (3, 4, 5), \'kwarg2\', {\'bar\': \'bar\', \'baz\': \'baz\'})\n</code></pre>\n<p>Also, <code>*</code> can be used by itself  to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.</p>\n<pre><code>def foo(arg, kwarg=None, *, kwarg2=None, **kwargs): \n    return arg, kwarg, kwarg2, kwargs\n</code></pre>\n<p>Here, <code>kwarg2</code> again must be an explicitly named, keyword argument:</p>\n<pre><code>&gt;&gt;&gt; foo(1,2,kwarg2=\'kwarg2\', foo=\'foo\', bar=\'bar\')\n(1, 2, \'kwarg2\', {\'foo\': \'foo\', \'bar\': \'bar\'})\n</code></pre>\n<p>And we can no longer accept unlimited positional arguments because we don\'t have <code>*args*</code>:</p>\n<pre><code>&gt;&gt;&gt; foo(1,2,3,4,5, kwarg2=\'kwarg2\', foo=\'foo\', bar=\'bar\')\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: foo() takes from 1 to 2 positional arguments \n    but 5 positional arguments (and 1 keyword-only argument) were given\n</code></pre>\n<p>Again, more simply, here we require <code>kwarg</code> to be given by name, not positionally:</p>\n<pre><code>def bar(*, kwarg=None): \n    return kwarg\n</code></pre>\n<p>In this example, we see that if we try to pass <code>kwarg</code> positionally, we get an error:</p>\n<pre><code>&gt;&gt;&gt; bar(\'kwarg\')\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: bar() takes 0 positional arguments but 1 was given\n</code></pre>\n<p>We must explicitly pass the <code>kwarg</code> parameter as a keyword argument.</p>\n<pre><code>&gt;&gt;&gt; bar(kwarg=\'kwarg\')\n\'kwarg\'\n</code></pre>\n<h2>Python 2 compatible demos</h2>\n<p><code>*args</code> (typically said &quot;star-args&quot;) and <code>**kwargs</code> (stars can be implied by saying &quot;kwargs&quot;, but be explicit with &quot;double-star kwargs&quot;) are common idioms of Python for using the <code>*</code> and <code>**</code> notation. These specific variable names aren\'t required (e.g. you could use <code>*foos</code> and <code>**bars</code>), but a departure from convention is likely to enrage your fellow Python coders.</p>\n<p>We typically use these when we don\'t know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).</p>\n<p><strong>Example 1</strong></p>\n<p>The following function describes how they can be used, and demonstrates behavior. Note the named <code>b</code> argument will be consumed by the second positional argument before :</p>\n<pre><code>def foo(a, b=10, *args, **kwargs):\n    \'\'\'\n    this function takes required argument a, not required keyword argument b\n    and any number of unknown positional arguments and keyword arguments after\n    \'\'\'\n    print(\'a is a required argument, and its value is {0}\'.format(a))\n    print(\'b not required, its default value is 10, actual value: {0}\'.format(b))\n    # we can inspect the unknown arguments we were passed:\n    #  - args:\n    print(\'args is of type {0} and length {1}\'.format(type(args), len(args)))\n    for arg in args:\n        print(\'unknown arg: {0}\'.format(arg))\n    #  - kwargs:\n    print(\'kwargs is of type {0} and length {1}\'.format(type(kwargs),\n                                                        len(kwargs)))\n    for kw, arg in kwargs.items():\n        print(\'unknown kwarg - kw: {0}, arg: {1}\'.format(kw, arg))\n    # But we don\'t have to know anything about them \n    # to pass them to other functions.\n    print(\'Args or kwargs can be passed without knowing what they are.\')\n    # max can take two or more positional args: max(a, b, c...)\n    print(\'e.g. max(a, b, *args) \\n{0}\'.format(\n      max(a, b, *args))) \n    kweg = \'dict({0})\'.format( # named args same as unknown kwargs\n      \', \'.join(\'{k}={v}\'.format(k=k, v=v) \n                             for k, v in sorted(kwargs.items())))\n    print(\'e.g. dict(**kwargs) (same as {kweg}) returns: \\n{0}\'.format(\n      dict(**kwargs), kweg=kweg))\n</code></pre>\n<p>We can check the online help for the function\'s signature, with <code>help(foo)</code>, which tells us</p>\n<pre><code>foo(a, b=10, *args, **kwargs)\n</code></pre>\n<p>Let\'s call this function with <code>foo(1, 2, 3, 4, e=5, f=6, g=7)</code></p>\n<p>which prints:</p>\n<pre><code>a is a required argument, and its value is 1\nb not required, its default value is 10, actual value: 2\nargs is of type &lt;type \'tuple\'&gt; and length 2\nunknown arg: 3\nunknown arg: 4\nkwargs is of type &lt;type \'dict\'&gt; and length 3\nunknown kwarg - kw: e, arg: 5\nunknown kwarg - kw: g, arg: 7\nunknown kwarg - kw: f, arg: 6\nArgs or kwargs can be passed without knowing what they are.\ne.g. max(a, b, *args) \n4\ne.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns: \n{\'e\': 5, \'g\': 7, \'f\': 6}\n</code></pre>\n<p><strong>Example 2</strong></p>\n<p>We can also call it using another function, into which we just provide <code>a</code>:</p>\n<pre><code>def bar(a):\n    b, c, d, e, f = 2, 3, 4, 5, 6\n    # dumping every local variable into foo as a keyword argument \n    # by expanding the locals dict:\n    foo(**locals()) \n</code></pre>\n<p><code>bar(100)</code> prints:</p>\n<pre><code>a is a required argument, and its value is 100\nb not required, its default value is 10, actual value: 2\nargs is of type &lt;type \'tuple\'&gt; and length 0\nkwargs is of type &lt;type \'dict\'&gt; and length 4\nunknown kwarg - kw: c, arg: 3\nunknown kwarg - kw: e, arg: 5\nunknown kwarg - kw: d, arg: 4\nunknown kwarg - kw: f, arg: 6\nArgs or kwargs can be passed without knowing what they are.\ne.g. max(a, b, *args) \n100\ne.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns: \n{\'c\': 3, \'e\': 5, \'d\': 4, \'f\': 6}\n</code></pre>\n<p><strong>Example 3: practical usage in decorators</strong></p>\n<p>OK, so maybe we\'re not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.</p>\n<pre><code>def foo(a, b, c, d=0, e=100):\n    # imagine this is much more code than a simple function call\n    preprocess() \n    differentiating_process_foo(a,b,c,d,e)\n    # imagine this is much more code than a simple function call\n    postprocess()\n\ndef bar(a, b, c=None, d=0, e=100, f=None):\n    preprocess()\n    differentiating_process_bar(a,b,c,d,e,f)\n    postprocess()\n\ndef baz(a, b, c, d, e, f):\n    ... and so on\n</code></pre>\n<p>We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how <code>*args</code> and <code>**kwargs</code> can be very useful:</p>\n<pre><code>def decorator(function):\n    \'\'\'function to wrap other functions with a pre- and postprocess\'\'\'\n    @functools.wraps(function) # applies module, name, and docstring to wrapper\n    def wrapper(*args, **kwargs):\n        # again, imagine this is complicated, but we only write it once!\n        preprocess()\n        function(*args, **kwargs)\n        postprocess()\n    return wrapper\n</code></pre>\n<p>And now every wrapped function can be written much more succinctly, as we\'ve factored out the redundancy:</p>\n<pre><code>@decorator\ndef foo(a, b, c, d=0, e=100):\n    differentiating_process_foo(a,b,c,d,e)\n\n@decorator\ndef bar(a, b, c=None, d=0, e=100, f=None):\n    differentiating_process_bar(a,b,c,d,e,f)\n\n@decorator\ndef baz(a, b, c=None, d=0, e=100, f=None, g=None):\n    differentiating_process_baz(a,b,c,d,e,f, g)\n\n@decorator\ndef quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):\n    differentiating_process_quux(a,b,c,d,e,f,g,h)\n</code></pre>\n<p>And by factoring out our code, which <code>*args</code> and <code>**kwargs</code> allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.</p>\n'}, {'answer_id': 32031804, 'author': 'quiet_penguin', 'author_id': 1086143, 'author_profile': 'https://Stackoverflow.com/users/1086143', 'pm_score': 3, 'selected': False, 'text': '<p>In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write <code>__init__</code> method in Python. Similar usage can seen in frameworks like Django code.</p>\n\n<p>For example,</p>\n\n<pre><code>def __init__(self, *args, **kwargs):\n    for attribute_name, value in zip(self._expected_attributes, args):\n        setattr(self, attribute_name, value)\n        if kwargs.has_key(attribute_name):\n            kwargs.pop(attribute_name)\n\n    for attribute_name in kwargs.viewkeys():\n        setattr(self, attribute_name, kwargs[attribute_name])\n</code></pre>\n\n<p>A subclass can then be</p>\n\n<pre><code>class RetailItem(Item):\n    _expected_attributes = Item._expected_attributes + [\'name\', \'price\', \'category\', \'country_of_origin\']\n\nclass FoodItem(RetailItem):\n    _expected_attributes = RetailItem._expected_attributes +  [\'expiry_date\']\n</code></pre>\n\n<p>The subclass then be instantiated as </p>\n\n<pre><code>food_item = FoodItem(name = \'Jam\', \n                     price = 12.0, \n                     category = \'Foods\', \n                     country_of_origin = \'US\', \n                     expiry_date = datetime.datetime.now())\n</code></pre>\n\n<p>Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class <code>__init__</code> to offload the attributes setting.\nThis is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,</p>\n\n<pre><code>class ElectronicAccessories(RetailItem):\n    _expected_attributes = RetailItem._expected_attributes +  [\'specifications\']\n    # Depend on args and kwargs to populate the data as needed.\n    def __init__(self, specifications = None, *args, **kwargs):\n        self.specifications = specifications  # Rest of attributes will make sense to parent class.\n        super(ElectronicAccessories, self).__init__(*args, **kwargs)\n</code></pre>\n\n<p>which can be instatiated as</p>\n\n<pre><code>usb_key = ElectronicAccessories(name = \'Sandisk\', \n                                price = \'$6.00\', \n                                category = \'Electronics\',\n                                country_of_origin = \'CN\',\n                                specifications = \'4GB USB 2.0/USB 3.0\')\n</code></pre>\n\n<p>The complete code is <a href="http://harisankar-krishnaswamy.blogspot.sg/2015/08/using-args-and-kwargs-python-code-post.html" rel="noreferrer">here</a></p>\n'}, {'answer_id': 34166505, 'author': 'leewz', 'author_id': 2963903, 'author_profile': 'https://Stackoverflow.com/users/2963903', 'pm_score': 4, 'selected': False, 'text': '<p>In Python 3.5, you can also use this syntax in <code>list</code>, <code>dict</code>, <code>tuple</code>, and <code>set</code> displays (also sometimes called literals). See <a href="http://legacy.python.org/dev/peps/pep-0448/" rel="noreferrer">PEP 488: Additional Unpacking Generalizations</a>.</p>\n\n<pre><code>&gt;&gt;&gt; (0, *range(1, 4), 5, *range(6, 8))\n(0, 1, 2, 3, 5, 6, 7)\n&gt;&gt;&gt; [0, *range(1, 4), 5, *range(6, 8)]\n[0, 1, 2, 3, 5, 6, 7]\n&gt;&gt;&gt; {0, *range(1, 4), 5, *range(6, 8)}\n{0, 1, 2, 3, 5, 6, 7}\n&gt;&gt;&gt; d = {\'one\': 1, \'two\': 2, \'three\': 3}\n&gt;&gt;&gt; e = {\'six\': 6, \'seven\': 7}\n&gt;&gt;&gt; {\'zero\': 0, **d, \'five\': 5, **e}\n{\'five\': 5, \'seven\': 7, \'two\': 2, \'one\': 1, \'three\': 3, \'six\': 6, \'zero\': 0}\n</code></pre>\n\n<p>It also allows multiple iterables to be unpacked in a single function call.</p>\n\n<pre><code>&gt;&gt;&gt; range(*[1, 10], *[2])\nrange(1, 10, 2)\n</code></pre>\n\n<p>(Thanks to mgilson for the PEP link.)</p>\n'}, {'answer_id': 34899056, 'author': 'mrtechmaker', 'author_id': 1542490, 'author_profile': 'https://Stackoverflow.com/users/1542490', 'pm_score': 6, 'selected': False, 'text': "<p>Let us first understand what are positional arguments and keyword arguments.\nBelow is an example of function definition with <strong>Positional arguments.</strong></p>\n\n<pre><code>def test(a,b,c):\n     print(a)\n     print(b)\n     print(c)\n\ntest(1,2,3)\n#output:\n1\n2\n3\n</code></pre>\n\n<p>So this is a function definition with positional arguments.\nYou can call it with keyword/named arguments as well:</p>\n\n<pre><code>def test(a,b,c):\n     print(a)\n     print(b)\n     print(c)\n\ntest(a=1,b=2,c=3)\n#output:\n1\n2\n3\n</code></pre>\n\n<p>Now let us study an example of function definition with <strong>keyword arguments</strong>:</p>\n\n<pre><code>def test(a=0,b=0,c=0):\n     print(a)\n     print(b)\n     print(c)\n     print('-------------------------')\n\ntest(a=1,b=2,c=3)\n#output :\n1\n2\n3\n-------------------------\n</code></pre>\n\n<p>You can call this function with positional arguments as well:</p>\n\n<pre><code>def test(a=0,b=0,c=0):\n    print(a)\n    print(b)\n    print(c)\n    print('-------------------------')\n\ntest(1,2,3)\n# output :\n1\n2\n3\n---------------------------------\n</code></pre>\n\n<p>So we now know function definitions with positional as well as keyword arguments.</p>\n\n<p>Now let us study the '*' operator and '**' operator.</p>\n\n<p>Please note these operators can be used in 2 areas:</p>\n\n<p>a) <strong>function call</strong></p>\n\n<p>b) <strong>function definition</strong></p>\n\n<p>The use of '*' operator and '**' operator in <strong>function call.</strong> </p>\n\n<p>Let us get straight to an example and then discuss it.</p>\n\n<pre><code>def sum(a,b):  #receive args from function calls as sum(1,2) or sum(a=1,b=2)\n    print(a+b)\n\nmy_tuple = (1,2)\nmy_list = [1,2]\nmy_dict = {'a':1,'b':2}\n\n# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator\nsum(*my_tuple)   # becomes same as sum(1,2) after unpacking my_tuple with '*'\nsum(*my_list)    # becomes same as sum(1,2) after unpacking my_list with  '*'\nsum(**my_dict)   # becomes same as sum(a=1,b=2) after unpacking by '**' \n\n# output is 3 in all three calls to sum function.\n</code></pre>\n\n<p>So remember </p>\n\n<p>when the '*' or '**' operator is used in a <strong>function call</strong> -</p>\n\n<p>'*' operator unpacks data structure such as a list or tuple  into arguments needed by function definition.</p>\n\n<p>'**' operator unpacks a dictionary into arguments needed by function definition.</p>\n\n<p>Now let us study the '*' operator use in <strong>function definition</strong>.\nExample:</p>\n\n<pre><code>def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))\n    sum = 0\n    for a in args:\n        sum+=a\n    print(sum)\n\nsum(1,2,3,4)  #positional args sent to function sum\n#output:\n10\n</code></pre>\n\n<p>In function <strong>definition</strong> the '*' operator packs the received arguments into a tuple.</p>\n\n<p>Now let us see an example of '**' used in function definition:</p>\n\n<pre><code>def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})\n    sum=0\n    for k,v in args.items():\n        sum+=v\n    print(sum)\n\nsum(a=1,b=2,c=3,d=4) #positional args sent to function sum\n</code></pre>\n\n<p>In function <strong>definition</strong> The '**' operator packs the received arguments into a dictionary.</p>\n\n<p>So remember:</p>\n\n<p>In a <strong>function call</strong> the '*' <strong>unpacks</strong> data structure of tuple or list into positional or keyword arguments to be received by function definition.</p>\n\n<p>In a <strong>function call</strong> the '**' <strong>unpacks</strong> data structure of dictionary into positional or keyword arguments to be received by function definition.</p>\n\n<p>In a <strong>function definition</strong> the '*' <strong>packs</strong> positional arguments into a tuple.</p>\n\n<p>In a <strong>function definition</strong> the '**' <strong>packs</strong> keyword arguments into a dictionary.</p>\n"}, {'answer_id': 40262722, 'author': 'amir jj', 'author_id': 3066559, 'author_profile': 'https://Stackoverflow.com/users/3066559', 'pm_score': 2, 'selected': False, 'text': "<p>A good example of using both in a function is:</p>\n\n<pre><code>&gt;&gt;&gt; def foo(*arg,**kwargs):\n...     print arg\n...     print kwargs\n&gt;&gt;&gt;\n&gt;&gt;&gt; a = (1, 2, 3)\n&gt;&gt;&gt; b = {'aa': 11, 'bb': 22}\n&gt;&gt;&gt;\n&gt;&gt;&gt;\n&gt;&gt;&gt; foo(*a,**b)\n(1, 2, 3)\n{'aa': 11, 'bb': 22}\n&gt;&gt;&gt;\n&gt;&gt;&gt;\n&gt;&gt;&gt; foo(a,**b) \n((1, 2, 3),)\n{'aa': 11, 'bb': 22}\n&gt;&gt;&gt;\n&gt;&gt;&gt;\n&gt;&gt;&gt; foo(a,b) \n((1, 2, 3), {'aa': 11, 'bb': 22})\n{}\n&gt;&gt;&gt;\n&gt;&gt;&gt;\n&gt;&gt;&gt; foo(a,*b)\n((1, 2, 3), 'aa', 'bb')\n{}\n</code></pre>\n"}, {'answer_id': 40492308, 'author': "Lochu'an Chang", 'author_id': 7132449, 'author_profile': 'https://Stackoverflow.com/users/7132449', 'pm_score': 4, 'selected': False, 'text': "<p>I want to give an example which others haven't  mentioned</p>\n<p>* can also unpack a <strong>generator</strong></p>\n<p>An example from Python3 Document</p>\n<pre><code>x = [1, 2, 3]\ny = [4, 5, 6]\n\nunzip_x, unzip_y = zip(*zip(x, y))\n</code></pre>\n<p>unzip_x will be (1, 2, 3), unzip_y will be (4, 5, 6)</p>\n<p>The zip() receives multiple iretable args, and return a generator.</p>\n<pre><code>zip(*zip(x,y)) -&gt; zip((1, 4), (2, 5), (3, 6))\n</code></pre>\n"}, {'answer_id': 40823181, 'author': 'thanhtang', 'author_id': 5098762, 'author_profile': 'https://Stackoverflow.com/users/5098762', 'pm_score': 2, 'selected': False, 'text': '<p>This example would help you remember <code>*args</code>, <code>**kwargs</code> and even <code>super</code> and inheritance in Python at once.</p>\n\n<pre><code>class base(object):\n    def __init__(self, base_param):\n        self.base_param = base_param\n\n\nclass child1(base): # inherited from base class\n    def __init__(self, child_param, *args) # *args for non-keyword args\n        self.child_param = child_param\n        super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg\n\nclass child2(base):\n    def __init__(self, child_param, **kwargs):\n        self.child_param = child_param\n        super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg\n\nc1 = child1(1,0)\nc2 = child2(1,base_param=0)\nprint c1.base_param # 0\nprint c1.child_param # 1\nprint c2.base_param # 0\nprint c2.child_param # 1\n</code></pre>\n'}, {'answer_id': 47580283, 'author': 'Brad Solomon', 'author_id': 7954504, 'author_profile': 'https://Stackoverflow.com/users/7954504', 'pm_score': 6, 'selected': False, 'text': '<p>This table is handy for using <code>*</code> and <code>**</code> in function <em>construction</em> and function <em>call</em>:</p>\n\n<pre><code>            In function construction         In function call\n=======================================================================\n          |  def f(*args):                 |  def f(a, b):\n*args     |      for arg in args:          |      return a + b\n          |          print(arg)            |  args = (1, 2)\n          |  f(1, 2)                       |  f(*args)\n----------|--------------------------------|---------------------------\n          |  def f(a, b):                  |  def f(a, b):\n**kwargs  |      return a + b              |      return a + b\n          |  def g(**kwargs):              |  kwargs = dict(a=1, b=2)\n          |      return f(**kwargs)        |  f(**kwargs)\n          |  g(a=1, b=2)                   |\n-----------------------------------------------------------------------\n</code></pre>\n\n<p>This really just serves to summarize Lorin Hochstein\'s <a href="https://stackoverflow.com/a/36926/7954504">answer</a> but I find it helpful.</p>\n\n<p>Relatedly: uses for the star/splat operators have been <a href="https://docs.python.org/3/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations" rel="noreferrer">expanded</a> in Python 3</p>\n'}, {'answer_id': 50116852, 'author': 'Hrvoje', 'author_id': 2119941, 'author_profile': 'https://Stackoverflow.com/users/2119941', 'pm_score': 2, 'selected': False, 'text': '<p><code>*args</code> and <code>**kwargs</code>: allow you to pass a variable number of arguments to a function. </p>\n\n<p><code>*args</code>: is used to send a non-keyworded variable length argument list to the function:</p>\n\n<pre><code>def args(normal_arg, *argv):\n    print("normal argument:", normal_arg)\n\n    for arg in argv:\n        print("Argument in list of arguments from *argv:", arg)\n\nargs(\'animals\', \'fish\', \'duck\', \'bird\')\n</code></pre>\n\n<p>Will produce:</p>\n\n<pre class="lang-none prettyprint-override"><code>normal argument: animals\nArgument in list of arguments from *argv: fish\nArgument in list of arguments from *argv: duck\nArgument in list of arguments from *argv: bird\n</code></pre>\n\n<p><code>**kwargs*</code></p>\n\n<p><code>**kwargs</code> allows you to pass keyworded variable length of arguments to a function. You should use <code>**kwargs</code> if you want to handle named arguments in a function. </p>\n\n<pre><code>def who(**kwargs):\n    if kwargs is not None:\n        for key, value in kwargs.items():\n            print("Your %s is %s." % (key, value))\n\nwho(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")  \n</code></pre>\n\n<p>Will produce:</p>\n\n<pre class="lang-none prettyprint-override"><code>Your name is Nikola.\nYour last_name is Tesla.\nYour birthday is 7.10.1856.\nYour birthplace is Croatia.\n</code></pre>\n'}, {'answer_id': 50461663, 'author': 'Miladiouss', 'author_id': 7428659, 'author_profile': 'https://Stackoverflow.com/users/7428659', 'pm_score': 5, 'selected': False, 'text': '<h2>For those of you who learn by examples!</h2>\n\n<ol>\n<li>The purpose of <code>*</code>  is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g. <code>f(*myList)</code> ).</li>\n<li>The purpose of <code>**</code> is to give you the ability to feed a function\'s arguments by providing a dictionary (e.g. <code>f(**{\'x\' : 1, \'y\' : 2})</code> ).</li>\n</ol>\n\n<p>Let us show this by defining a function that takes two normal variables <code>x</code>, <code>y</code>, and can accept more arguments as <code>myArgs</code>, and can accept even more arguments as <code>myKW</code>. Later, we will show how to feed <code>y</code> using <code>myArgDict</code>.</p>\n\n<pre><code>def f(x, y, *myArgs, **myKW):\n    print("# x      = {}".format(x))\n    print("# y      = {}".format(y))\n    print("# myArgs = {}".format(myArgs))\n    print("# myKW   = {}".format(myKW))\n    print("# ----------------------------------------------------------------------")\n\n# Define a list for demonstration purposes\nmyList    = ["Left", "Right", "Up", "Down"]\n# Define a dictionary for demonstration purposes\nmyDict    = {"Wubba": "lubba", "Dub": "dub"}\n# Define a dictionary to feed y\nmyArgDict = {\'y\': "Why?", \'y0\': "Why not?", "q": "Here is a cue!"}\n\n# The 1st elem of myList feeds y\nf("myEx", *myList, **myDict)\n# x      = myEx\n# y      = Left\n# myArgs = (\'Right\', \'Up\', \'Down\')\n# myKW   = {\'Wubba\': \'lubba\', \'Dub\': \'dub\'}\n# ----------------------------------------------------------------------\n\n# y is matched and fed first\n# The rest of myArgDict becomes additional arguments feeding myKW\nf("myEx", **myArgDict)\n# x      = myEx\n# y      = Why?\n# myArgs = ()\n# myKW   = {\'y0\': \'Why not?\', \'q\': \'Here is a cue!\'}\n# ----------------------------------------------------------------------\n\n# The rest of myArgDict becomes additional arguments feeding myArgs\nf("myEx", *myArgDict)\n# x      = myEx\n# y      = y\n# myArgs = (\'y0\', \'q\')\n# myKW   = {}\n# ----------------------------------------------------------------------\n\n# Feed extra arguments manually and append even more from my list\nf("myEx", 4, 42, 420, *myList, *myDict, **myDict)\n# x      = myEx\n# y      = 4\n# myArgs = (42, 420, \'Left\', \'Right\', \'Up\', \'Down\', \'Wubba\', \'Dub\')\n# myKW   = {\'Wubba\': \'lubba\', \'Dub\': \'dub\'}\n# ----------------------------------------------------------------------\n\n# Without the stars, the entire provided list and dict become x, and y:\nf(myList, myDict)\n# x      = [\'Left\', \'Right\', \'Up\', \'Down\']\n# y      = {\'Wubba\': \'lubba\', \'Dub\': \'dub\'}\n# myArgs = ()\n# myKW   = {}\n# ----------------------------------------------------------------------\n</code></pre>\n\n<h3>Caveats</h3>\n\n<ol>\n<li><code>**</code> is exclusively reserved for dictionaries.</li>\n<li>Non-optional argument assignment happens first.</li>\n<li>You cannot use a non-optional argument twice.</li>\n<li>If applicable, <code>**</code> must come after <code>*</code>, always.</li>\n</ol>\n'}, {'answer_id': 51733267, 'author': 'ishandutta2007', 'author_id': 865220, 'author_profile': 'https://Stackoverflow.com/users/865220', 'pm_score': 4, 'selected': False, 'text': '<p><code>*</code> means receive variable arguments as tuple</p>\n\n<p><code>**</code> means receive variable arguments as dictionary</p>\n\n<p>Used like the following:</p>\n\n<p><strong>1) single *</strong></p>\n\n<pre><code>def foo(*args):\n    for arg in args:\n        print(arg)\n\nfoo("two", 3)\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>two\n3\n</code></pre>\n\n<p><strong>2) Now <code>**</code></strong></p>\n\n<pre><code>def bar(**kwargs):\n    for key in kwargs:\n        print(key, kwargs[key])\n\nbar(dic1="two", dic2=3)\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>dic1 two\ndic2 3\n</code></pre>\n'}, {'answer_id': 52134172, 'author': 'Premraj', 'author_id': 1697099, 'author_profile': 'https://Stackoverflow.com/users/1697099', 'pm_score': 0, 'selected': False, 'text': '<ul>\n<li><code>def foo(param1, *param2):</code> is a method can accept arbitrary number of values for <code>*param2</code>,</li>\n<li><code>def bar(param1, **param2):</code> is a method can accept arbitrary number of values with keys for <code>*param2</code></li>\n<li><code>param1</code> is a simple parameter.</li>\n</ul>\n\n<p>For example, the syntax for implementing <strong>varargs</strong> in Java as follows:</p>\n\n<pre><code>accessModifier methodName(datatype… arg) {\n    // method body\n}\n</code></pre>\n'}, {'answer_id': 55475113, 'author': 'RBF06', 'author_id': 3311728, 'author_profile': 'https://Stackoverflow.com/users/3311728', 'pm_score': 4, 'selected': False, 'text': '<h2>TL;DR</h2>\n<p>It packs arguments passed to the function into <code>list</code> and <code>dict</code> respectively inside the function body. When you define a function signature like this:</p>\n<pre class="lang-py prettyprint-override"><code>def func(*args, **kwds):\n    # do stuff\n</code></pre>\n<p>it can be called with any number of arguments and keyword arguments. The non-keyword arguments get packed into a list called <code>args</code> inside the function body and the keyword arguments get packed into a dict called <code>kwds</code> inside the function body.</p>\n<pre class="lang-py prettyprint-override"><code>func(&quot;this&quot;, &quot;is a list of&quot;, &quot;non-keyowrd&quot;, &quot;arguments&quot;, keyword=&quot;ligma&quot;, options=[1,2,3])\n</code></pre>\n<p>now inside the function body, when the function is called, there are two local variables, <code>args</code> which is a list having value <code>[&quot;this&quot;, &quot;is a list of&quot;, &quot;non-keyword&quot;, &quot;arguments&quot;]</code> and <code>kwds</code> which is a <code>dict</code> having value <code>{&quot;keyword&quot; : &quot;ligma&quot;, &quot;options&quot; : [1,2,3]}</code></p>\n<hr />\n<p>This also works in reverse, i.e. from the caller side. for example if you have a function defined as:</p>\n<pre class="lang-py prettyprint-override"><code>def f(a, b, c, d=1, e=10):\n    # do stuff\n</code></pre>\n<p>you can call it with by unpacking iterables or mappings you have in the calling scope:</p>\n<pre class="lang-py prettyprint-override"><code>iterable = [1, 20, 500]\nmapping = {&quot;d&quot; : 100, &quot;e&quot;: 3}\nf(*iterable, **mapping)\n# That call is equivalent to\nf(1, 20, 500, d=100, e=3)\n</code></pre>\n'}, {'answer_id': 56962836, 'author': 'Raj', 'author_id': 8588359, 'author_profile': 'https://Stackoverflow.com/users/8588359', 'pm_score': 3, 'selected': False, 'text': '<p>Building on nickd\'s <a href="https://stackoverflow.com/a/36911/8588359">answer</a>...</p>\n\n<pre><code>def foo(param1, *param2):\n    print(param1)\n    print(param2)\n\n\ndef bar(param1, **param2):\n    print(param1)\n    print(param2)\n\n\ndef three_params(param1, *param2, **param3):\n    print(param1)\n    print(param2)\n    print(param3)\n\n\nfoo(1, 2, 3, 4, 5)\nprint("\\n")\nbar(1, a=2, b=3)\nprint("\\n")\nthree_params(1, 2, 3, 4, s=5)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1\n(2, 3, 4, 5)\n\n1\n{\'a\': 2, \'b\': 3}\n\n1\n(2, 3, 4)\n{\'s\': 5}\n</code></pre>\n\n<p>Basically, any number of <strong>positional arguments</strong> can use *args and any <strong>named arguments</strong> (or kwargs aka keyword arguments) can use **kwargs.</p>\n'}, {'answer_id': 59217020, 'author': 'dreftymac', 'author_id': 42223, 'author_profile': 'https://Stackoverflow.com/users/42223', 'pm_score': 2, 'selected': False, 'text': '<h2>Context</h2>\n\n<ul>\n<li>python 3.x</li>\n<li>unpacking with <code>**</code></li>\n<li>use with string formatting</li>\n</ul>\n\n<h2>Use with string formatting</h2>\n\n<p>In addition to the answers in this thread, here is another detail that was not mentioned elsewhere. This expands on the <a href="https://stackoverflow.com/a/47580283/42223">answer by Brad Solomon</a></p>\n\n<p>Unpacking with <code>**</code> is also useful when using python <code>str.format</code>.  </p>\n\n<p>This is somewhat similar to what you can do with python <code>f-strings</code> <a href="https://stackoverflow.com/questions/tagged/f-string">f-string</a> but with the added overhead of declaring a dict to hold the variables (f-string does not require a dict).</p>\n\n<h2>Quick Example</h2>\n\n<pre class="lang-py prettyprint-override"><code>  ## init vars\n  ddvars = dict()\n  ddcalc = dict()\n  pass\n  ddvars[\'fname\']     = \'Huomer\'\n  ddvars[\'lname\']     = \'Huimpson\'\n  ddvars[\'motto\']     = \'I love donuts!\'\n  ddvars[\'age\']       = 33\n  pass\n  ddcalc[\'ydiff\']     = 5\n  ddcalc[\'ycalc\']     = ddvars[\'age\'] + ddcalc[\'ydiff\']\n  pass\n  vdemo = []\n\n  ## ********************\n  ## single unpack supported in py 2.7\n  vdemo.append(\'\'\'\n  Hello {fname} {lname}!\n\n  Today you are {age} years old!\n\n  We love your motto "{motto}" and we agree with you!\n  \'\'\'.format(**ddvars)) \n  pass\n\n  ## ********************\n  ## multiple unpack supported in py 3.x\n  vdemo.append(\'\'\'\n  Hello {fname} {lname}!\n\n  In {ydiff} years you will be {ycalc} years old!\n  \'\'\'.format(**ddvars,**ddcalc)) \n  pass\n\n  ## ********************\n  print(vdemo[-1])\n\n</code></pre>\n'}, {'answer_id': 59630576, 'author': 'Meysam Sadeghi', 'author_id': 3484477, 'author_profile': 'https://Stackoverflow.com/users/3484477', 'pm_score': 5, 'selected': False, 'text': '<p><strong>TL;DR</strong></p>\n<p>Below are 6 different use cases for <code>*</code> and <code>**</code> in python programming:</p>\n<ol>\n<li><strong>To accept any number of positional arguments using <code>*args</code>:</strong> <code>def foo(*args): pass</code>, here <code>foo</code> accepts any number of positional arguments, i. e., the following calls are valid <code>foo(1)</code>, <code>foo(1, \'bar\')</code></li>\n<li><strong>To accept any number of keyword arguments using <code>**kwargs</code>:</strong> <code>def foo(**kwargs): pass</code>, here \'foo\' accepts any number of keyword arguments, i. e., the following calls are valid <code>foo(name=\'Tom\')</code>, <code>foo(name=\'Tom\', age=33)</code></li>\n<li><strong>To accept any number of positional and keyword arguments using <code>*args, **kwargs</code>:</strong> <code>def foo(*args, **kwargs): pass</code>, here <code>foo</code> accepts any number of positional and keyword arguments, i. e., the following calls are valid <code>foo(1,name=\'Tom\')</code>, <code>foo(1, \'bar\', name=\'Tom\', age=33)</code></li>\n<li><strong>To enforce keyword only arguments using <code>*</code>:</strong> <code>def foo(pos1, pos2, *, kwarg1): pass</code>, here <code>*</code> means that foo only accept keyword arguments after pos2, hence <code>foo(1, 2, 3)</code> raises TypeError but <code>foo(1, 2, kwarg1=3)</code> is ok.</li>\n<li><strong>To express no further interest in more positional arguments using <code>*_</code> (Note: this is a convention only):</strong> <code>def foo(bar, baz, *_): pass</code> means (by convention) <code>foo</code> only uses <code>bar</code> and <code>baz</code> arguments in its working and will ignore others.</li>\n<li><strong>To express no further interest in more keyword arguments using <code>**_</code> (Note: this is a convention only):</strong> <code>def foo(bar, baz, **_): pass</code> means (by convention) <code>foo</code> only uses <code>bar</code> and <code>baz</code> arguments in its working and will ignore others.</li>\n</ol>\n<p><strong>BONUS:</strong> From python 3.8 onward, one can use <code>/</code> in function definition to enforce  positional only parameters. In the following example, parameters a and b are <strong>positional-only</strong>, while c or d can be positional or keyword, and e or f are required to be keywords:</p>\n<pre><code>def f(a, b, /, c, d, *, e, f):\n    pass\n</code></pre>\n<p><strong>BONUS 2</strong>: <a href="https://stackoverflow.com/a/21809162/3484477">THIS ANSWER</a> to the same question also brings a new perspective, where it shares what does <code>*</code> and <code>**</code> means in a <code>function call</code>, <code>functions signature</code>, <code>for loops</code>, etc.</p>\n'}, {'answer_id': 62442187, 'author': 'etoricky', 'author_id': 4710031, 'author_profile': 'https://Stackoverflow.com/users/4710031', 'pm_score': 3, 'selected': False, 'text': '<p>Given a function that has 3 items as argument</p>\n\n<pre><code>sum = lambda x, y, z: x + y + z\nsum(1,2,3) # sum 3 items\n\nsum([1,2,3]) # error, needs 3 items, not 1 list\n\nx = [1,2,3][0]\ny = [1,2,3][1]\nz = [1,2,3][2]\nsum(x,y,z) # ok\n\nsum(*[1,2,3]) # ok, 1 list becomes 3 items\n</code></pre>\n\n<p>Imagine this toy with a bag of a triangle, a circle and a rectangle item. That bag does not directly fit. You need to unpack the bag to take those 3 items and now they fit. The Python * operator does this unpack process.</p>\n\n<p><a href="https://i.stack.imgur.com/9gf2j.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/9gf2j.jpg" alt="enter image description here"></a></p>\n'}, {'answer_id': 66705594, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>*args ( or *any ) means every parameters</p>\n<pre class="lang-py prettyprint-override"><code>def any_param(*param):\n    pass\n\nany_param(1)\nany_param(1,1)\nany_param(1,1,1)\nany_param(1,...)\n</code></pre>\n<p><em>NOTICE</em> : you can don\'t pass parameters to *args</p>\n<pre class="lang-py prettyprint-override"><code>def any_param(*param):\n    pass\n\nany_param() # will work correct\n</code></pre>\n<p>The *args is in type tuple</p>\n<pre><code>def any_param(*param):\n    return type(param)\n\nany_param(1) #tuple\nany_param() # tuple\n</code></pre>\n<p>for access to elements don\'t use of *</p>\n<pre><code>def any(*param):\n    param[0] # correct\n\ndef any(*param):\n    *param[0] # incorrect\n</code></pre>\n<p>The **kwd</p>\n<p>**kwd or **any\nThis is a dict type</p>\n<pre><code>def func(**any):\n    return type(any) # dict\n\ndef func(**any):\n    return any\n\nfunc(width=&quot;10&quot;,height=&quot;20&quot;) # {width=&quot;10&quot;,height=&quot;20&quot;)\n\n\n</code></pre>\n'}, {'answer_id': 73178373, 'author': 'Isaac Vinícius', 'author_id': 16892196, 'author_profile': 'https://Stackoverflow.com/users/16892196', 'pm_score': 0, 'selected': False, 'text': '<h3>&quot;Infinite&quot; Args with *args and **kwargs</h3>\n<p><code>*args</code> and <code>**kwargs</code> are just some way to input unlimited characters to functions, like:</p>\n<pre class="lang-py prettyprint-override"><code>\ndef print_all(*args, **kwargs):\n    print(args) # print any number of arguments like: &quot;print_all(&quot;foo&quot;, &quot;bar&quot;)&quot;\n    print(kwargs.get(&quot;to_print&quot;)) # print the value of the keyworded argument &quot;to_print&quot;\n\n\n# example:\nprint_all(&quot;Hello&quot;, &quot;World&quot;, to_print=&quot;!&quot;)\n# will print:\n&quot;&quot;&quot;\n(\'Hello\', \'World\')\n!\n&quot;&quot;&quot;\n</code></pre>\n'}, {'answer_id': 74406075, 'author': 'Kai - Kazuya Ito', 'author_id': 8172439, 'author_profile': 'https://Stackoverflow.com/users/8172439', 'pm_score': 0, 'selected': False, 'text': '<ul>\n<li><p><strong><code>*args</code></strong> is the special parameter which can take 0 or more (positional) arguments as a tuple.</p>\n</li>\n<li><p><strong><code>**kwargs</code></strong> is the special parameter which can take 0 or more (keyword) arguments as a dictionary.</p>\n</li>\n</ul>\n<p>*In Python, there are 2 kinds of arguments <a href="https://docs.python.org/3/glossary.html#term-argument" rel="nofollow noreferrer"><strong>positional argument and keyword argument</strong></a>:</p>\n<h2><code>*args</code>:</h2>\n<p>For example, <code>*args</code> can take 0 or more arguments as a tuple as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>           ↓\ndef test(*args):\n    print(args)\n\ntest() # Here\ntest(1, 2, 3, 4) # Here\ntest((1, 2, 3, 4)) # Here\ntest(*(1, 2, 3, 4)) # Here\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>()\n(1, 2, 3, 4)\n((1, 2, 3, 4),)\n(1, 2, 3, 4)\n</code></pre>\n<p>And, when printing <code>*args</code>, 4 numbers are printed without parentheses and commas:</p>\n<pre class="lang-py prettyprint-override"><code>def test(*args):\n    print(*args) # Here\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>1 2 3 4\n</code></pre>\n<p>And, <code>args</code> has <strong>tuple</strong> type:</p>\n<pre class="lang-py prettyprint-override"><code>def test(*args):\n    print(type(args)) # Here\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>&lt;class \'tuple\'&gt;\n</code></pre>\n<p>But, <code>*args</code> has no type:</p>\n<pre class="lang-py prettyprint-override"><code>def test(*args):\n    print(type(*args)) # Here\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>TypeError: type() takes 1 or 3 arguments</p>\n</blockquote>\n<p>And, normal parameters can be put before <code>*args</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>          ↓     ↓\ndef test(num1, num2, *args):\n    print(num1, num2, args)\n    \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>1 2 (3, 4)\n</code></pre>\n<p>But, <code>**kwargs</code> cannot be put before <code>*args</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>             ↓     \ndef test(**kwargs, *args):\n    print(kwargs, args)\n    \ntest(num1=1, num2=2, 3, 4)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>SyntaxError: invalid syntax</p>\n</blockquote>\n<p>And, normal parameters cannot be put after <code>*args</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>                 ↓     ↓\ndef test(*args, num1, num2):\n    print(args, num1, num2)\n    \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>TypeError: test() missing 2 required keyword-only arguments: \'num1\' and \'num2\'</p>\n</blockquote>\n<p>But, if normal parameters have default values, they can be put after <code>*args</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>                      ↓         ↓\ndef test(*args, num1=100, num2=None):\n    print(args, num1, num2)\n    \ntest(1, 2, num1=3, num2=4)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>(1, 2) 3 4\n</code></pre>\n<p>And also, <code>**kwargs</code> can be put after <code>*args</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>                    ↓\ndef test(*args, **kwargs):\n    print(args, kwargs)\n    \ntest(1, 2, num1=3, num2=4)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>(1, 2) {\'num1\': 3, \'num2\': 4}\n</code></pre>\n<h2><code>**kwargs</code>:</h2>\n<p>For example, <code>**kwargs</code> can take 0 or more arguments as a dictionary as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>             ↓\ndef test(**kwargs):\n    print(kwargs)\n\ntest() # Here\ntest(name=&quot;John&quot;, age=27) # Here\ntest(**{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 27}) # Here\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>{}\n{\'name\': \'John\', \'age\': 27}\n{\'name\': \'John\', \'age\': 27}\n</code></pre>\n<p>And, when printing <code>*kwargs</code>, 2 keys are printed:</p>\n<pre class="lang-py prettyprint-override"><code>def test(**kwargs):\n    print(*kwargs) # Here\n \ntest(name=&quot;John&quot;, age=27)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>name age\n</code></pre>\n<p>And, <code>kwargs</code> has <strong>dict</strong> type:</p>\n<pre class="lang-py prettyprint-override"><code>def test(**kwargs):\n    print(type(kwargs)) # Here\n \ntest(name=&quot;John&quot;, age=27)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>&lt;class \'dict\'&gt;\n</code></pre>\n<p>But, <code>*kwargs</code> and <code>**kwargs</code> have no type:</p>\n<pre class="lang-py prettyprint-override"><code>def test(**kwargs):\n    print(type(*kwargs)) # Here\n \ntest(name=&quot;John&quot;, age=27)\n</code></pre>\n<pre class="lang-py prettyprint-override"><code>def test(**kwargs):\n    print(type(**kwargs)) # Here\n \ntest(name=&quot;John&quot;, age=27)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>TypeError: type() takes 1 or 3 arguments</p>\n</blockquote>\n<p>And, normal parameters can be put before <code>**kwargs</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>          ↓     ↓\ndef test(num1, num2, **kwargs):\n    print(num1, num2, kwargs)\n\ntest(1, 2, name=&quot;John&quot;, age=27)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>1 2 {\'name\': \'John\', \'age\': 27}\n</code></pre>\n<p>And also, <code>*args</code> can be put before <code>**kwargs</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>           ↓\ndef test(*args, **kwargs):\n    print(args, kwargs)\n\ntest(1, 2, name=&quot;John&quot;, age=27)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>(1, 2) {\'name\': \'John\', \'age\': 27}\n</code></pre>\n<p>And, normal parameters and <code>*args</code> cannot be put after <code>**kwargs</code> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>                    ↓     ↓\ndef test(**kwargs, num1, num2):\n    print(kwargs, num1, num2)\n\ntest(name=&quot;John&quot;, age=27, 1, 2)\n</code></pre>\n<pre class="lang-py prettyprint-override"><code>                     ↓\ndef test(**kwargs, *args):\n    print(kwargs, args)\n\ntest(name=&quot;John&quot;, age=27, 1, 2)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>SyntaxError: invalid syntax</p>\n</blockquote>\n<h2>For both <code>*args</code> and <code>**kwargs</code>:</h2>\n<p>Actually, you can use other names for <code>*args</code> and <code>**kwargs</code> as shown below. <code>*args</code> and <code>**kwargs</code> are used conventionally:</p>\n<pre class="lang-py prettyprint-override"><code>            ↓        ↓\ndef test(*banana, **orange):\n    print(banana, orange)\n    \ntest(1, 2, num1=3, num2=4)\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>(1, 2) {\'num1\': 3, \'num2\': 4}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/36901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2572/']