*args and **kwargs in Python
Tags: python, programming
Published: 2024-03-28 01:16:25

<p>In this article you will learn how to use the single and double asterisk operators, to define functions that can take&nbsp; an arbitrary number of arguments. But before we dive on that, we first need to understand how arguments works in Python.</p>

<p>There are two two types of arguments,&nbsp;</p>

<div>
<ol>
	<li><strong>Positional arguments</strong></li>
	<li><strong>Keyword arguments.</strong></li>
</ol>
</div>

<p>Positional arguments are the arguments passed to a function in a specific order or position. The number of arguments and the order in which they are written is important. The following example shows a function that takes positional argument.</p>

<div class="autorun example">
<pre>
<code class="language-python">#a function that defines 3 parameters
def greatest(a, b, c):
    if a &gt; b:
        if a &gt; c:
             num = a
    elif a &gt; c:
         num = b
    else:
         num = c

    return num

#Calling the function using positional arguments.
result = greatest(18, 23, 4)
print(result)</code></pre>
</div>

<p>In the above example we defined a function, greatest(), that is meant to get the largest of 3 values. We used the function to illustrate how &nbsp;positional arguments works. Note that when calling the function,&nbsp; we simply passed 3 arguments to the function without explicitly specifying which argument is <code>a</code>, which one is <code>b </code>or which one is <code>c</code>. The arguments are&nbsp; assigned to the parameters in the same order they were passed. So in the example,&nbsp; the first argument(<code>18</code>) is assigned to the parameter <code>a</code>, the second one(<code>23</code>) is assigned to <code>b</code>, and the third one(<code>4</code>) is assigned to <code>c</code>.</p>

<p>Keyword arguments on the other hard, expects the values to be&nbsp;explicitly assigned to the corresponding parameters&nbsp;&nbsp;using<code> parameter = value</code> syntax. This way the order of arguments is&nbsp; not&nbsp;relevant. Consider the following example.</p>

<div class="autorun example">
<pre>
<code class="language-python">#a function that defines 3 parameters
def greatest(a, b, c):
    if a &gt; b:
        if a &gt; c:
             num = a
    elif a &gt; c:
         num = b
    else:
         num = c

    return num

#Calling the function using keyword arguments.
result = greatest(b = 23, a = 18, c = 4)
print(result)</code></pre>
</div>

<p>In the above example, we used keyword arguments when calling the <code>greatest() </code>function. In keyword arguments we are specifying which values belongs to which parameter. The order in which the arguments are passed is not important because&nbsp; we are explicitly specifying the parameter name.</p>

<h2>Starred parameters</h2>

<p>Starred parameters allows us to define functions that can take&nbsp;arbitrary&nbsp;number of positional or keyword arguments. For example, with the builtin<code> print()</code> function,&nbsp; we can pass in as&nbsp;many arguments as we want, and the function will print out each argument separately.&nbsp;</p>

<div class="autorun example">
<pre>
<code class="language-python">print('Hello', 'World', 'Welcome', 'to', 'Pynerds')</code></pre>
</div>

<p>In case with positional arguments, we use a single&nbsp;asterisk (*) followed by the name, while for keyword arguments, we use double asterisks(**) followed by the name of the parameter.</p>

<h3>Arbitrary positional arguments(&nbsp;<code>*args</code>)</h3>

<p>The single asterisk operator(<code>*</code>) is used in function parameters&nbsp;so as the&nbsp;&nbsp;function can takes an arbitrary number of positional arguments. By convention, the name<strong>&nbsp;&quot;args&quot;&nbsp;</strong>&nbsp;is used alongside the operator, however,&nbsp;this is just a convention,&nbsp; any other valid variable name can be used instead.&nbsp;&nbsp;&nbsp;Consider the following example:</p>

<div class="autorun example">
<pre>
<code class="language-python">def myfunc(*args):
    print(args)
    for i in args:
        print(i)

myfunc(7, 3, 1, 4, 10, 0)</code></pre>
</div>

<p>As shown in the above example,&nbsp;specifying the single asterisk parameter makes a function to effectively take in arbitrary number of positional arguments.</p>

<p>The arbitrary positional arguments are received inside the function as a standard tuple. We can, therefore, perform&nbsp;all tuple operations on them.</p>

<p>In the following example, we define the greatest() function, so that it takes any number of positional arguments rather than just three.</p>

<div class="autorun example">
<pre>
<code class="language-python">def greatest(*args):
     return max(args)

result = greatest(7, 11, 2, 10, 3)
print(result)</code></pre>
</div>

<h3>Arbitrary keyword arguments(&nbsp;<code>**kwargs</code>)</h3>

<p>The double asterisk parameter(<code>**</code>) is used to define a function that can take an arbitrary number of keyword arguments. Similarly, the convention is to use the name<strong> &quot;kwargs&quot;</strong> to refer to the arguments but&nbsp; any other valid name can also be used.</p>

<div class="autorun example">
<pre>
<code class="language-python">def func(**kwargs):
    print(kwargs)

func(a = 10, b = 20, c = 50, d = 120)</code></pre>
</div>

<p>The arguments are received inside the function as a standard dictionary. To access an element, we can use&nbsp;the name of the argument as the key.</p>

<div class="autorun example">
<pre>
<code class="language-python">def func(**kwargs):
    #access individual arguments
    print(kwargs['a'])
    print(kwargs['b'])
    print(kwargs['c'])
    print(kwargs['d'])

func(a = 10, b = 20, c = 50, d = 120)</code></pre>
</div>

<h3>*args and **kwargs together</h3>

<p>We can use both&nbsp;the single asterisk(<code>*args</code>) and the double asterisks <code>**kwarga&nbsp;</code>operators in the same function so that the function can handle arbitrary&nbsp;positional and keyword arguments at the same time. However,&nbsp;we must make sure that the parameter with the single asterisk(<code>*args</code>) always comes before&nbsp;&nbsp;the double&nbsp;asterisk parameter(<code>**kwargs</code>) in the function definition, otherwise, a <code>SyntaxError </code>exception will be raised.</p>

<div class="autorun example">
<pre>
<code class="language-python">def func(*args, **kwargs):
    print(args)
    print(kwargs)

func(10, 20, 30, a = 100, b = 300, c = 500)</code></pre>
</div>

<p>In the above example, we passed to the function both&nbsp;positional and keyword arguments. The&nbsp;&nbsp;positional arguments are received in the <code>args </code>tuple while the keyword arguments are received in the <code>kwargs </code>dictionary.</p>

<h3>*args and **kwargs alongside other parameters</h3>

<p>It is also possible to have other positional or keyword parameters alongside the <code>*args</code> and <code>**kwargs </code>parameters. This way, the<code>&nbsp;*args</code> parameters should come after all positional parameters and the<code> **kwargs</code>&nbsp;&nbsp;after all keyword parameters.</p>

<div class="autorun example">
<pre>
<code class="language-python">def func(a, b, *args, x = None, y = None, **kwargs):
      print(a, b)
      print(args)
      print(x, y)
      print(kwargs)

func(1, 2, 3, 4, 5, x = 10, y = 20, i = 100, j = 200, k = 300)</code></pre>
</div>

<p>As you can see above, the function knows where each argument belongs, whether it is a regular arguments or&nbsp;it belongs to the arbitrary positional or keywords arguments. It is upon the user to ensure that the arguments are correctly&nbsp;passed in accordance with the parameters&nbsp;specifications.</p>

<div class="related"><h3>Related articles</h3>
<hr>
<ul><li><p><a class="text-success" href="https://www.pynerds.com/partial-functions-in-python/">Partial functions in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/how-to-cache-function-results-in-python/">How to cache function results in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/difference-between-function-and-method-in-python/">Difference between function and method in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/invoke-a-function-using-a-string-name-in-python/">Invoke a function using a string name in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/unpacking-operation-in-python/">unpacking operation in Python</a><li><p><a class="text-success" href="https:www.pynerds.com/docstrings-in-python/">Docstrings in Python</a></ul></div>