Wednesday, January 13, 2021

Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python

In this article we’ll see what are variable length arguments (*args) in Python and what are keyword variable length arguments (**kwargs) in Python.


Variable length arguments in Python

A variable length argument as the name suggests is an argument that can accept variable number of values. To indicate that the function can take variable number of argument you write a variable argument using a ‘*’, for example *args.

Variable arguments help in the scenario where the exact number of arguments are not known in the beginning, it also helps to make your function more flexible. Consider the scenario where you have a function to add numbers.

def add_num(num1, num2):
    return num1 + num2

This function can only be used to add two numbers, if you pass more than two numbers you will get an error.

result = add_num(5, 6, 7)
print('Sum is', result)
    result = add_num(5, 6, 7)
TypeError: add_num() takes 2 positional arguments but 3 were given

By changing the argument to *args you can specify that function accepts variable number of arguments and can be used to sum ‘n’ numbers.

def add_num(*args):
  sum = 0
  for num in args:
      sum += num
  return sum

result = add_num(5, 6, 7)
print('Sum is', result)

result = add_num(5, 6, 7, 8)
print('Sum is', result)

result = add_num(5, 6, 7, 8, 9)
print('Sum is', result)

Output

Sum is 18
Sum is 26
Sum is 35

Points about variable length arguments in Python-

  1. It is not mandatory to name variable length argument as ‘*args’. What is required is *, variable name can be any variable name for example *numbers, *names.
  2. Using variable length argument you can pass zero or more arguments to a function.
  3. Values pass to *args are stored in a tuple.
  4. Before variable args you can have a formal argument but not after a variable args. After variable argument you can have keyword arguments.
    def add_num(n, *numbers):
      sum = 0
      print('n is', n)
      for num in numbers:
        sum += num
      sum += n
      return sum
    
    result = add_num(8, 5, 6, 7)
    print('Sum is', result)
    

    Output

    n is 8
    Sum is 26
    

As you can see here n is a formal argument and first value is passed to that argument.

If you change the function to have a formal argument after the variable length argument-

def add_num(*numbers, n):

Then it results in an error.

Output

    result = add_num(8, 5, 6, 7)
TypeError: add_num() missing 1 required keyword-only argument: 'n'

You can pass a keyword argument after variable args.

def add_num(*numbers, n):
  sum = 0
  print('n is', n)
  for num in numbers:
    sum += num
  sum += n
  return sum

result = add_num(5, 6, 7, n=8)
print('Sum is', result)

Output

n is 8
Sum is 26

Keyword variable length arguments in Python

Python keyword variable length argument is an argument that accept variable number of keyword arguments (arguments in the form of key, value pair). To indicate that the function can take keyword variable length argument you write an argument using double asterisk ‘**’, for example **kwargs.

Values passed as keyword variable length argument are stored in a dictionary that is referenced by the keyword arg name.

def display_records(**records):
  for k, v in records.items():
    print('{} = {}'.format(k,v))

display_records(Firstname="Jack", Lastname="Douglas", marks1=45, marks2=42)
display_records(Firstname="Lisa", Lastname="Montana", marks1=48, marks2=45, marks3=49)

Output

Firstname = Jack
Lastname = Douglas
marks1 = 45
marks2 = 42
Firstname = Lisa
Lastname = Montana
marks1 = 48
marks2 = 45
marks3 = 49

You can pass a formal argument before a keyword variable length argument but not after that so following is a valid function definition.

def display_records(a, **records):

That's all for this topic Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Functions: Returning Multiple Values
  2. Default Arguments in Python
  3. Global Keyword in Python With Examples
  4. Nonlocal Keyword in Python With Examples
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Check if String Present in Another String in Python
  2. Python assert Statement
  3. Method Overriding in Python
  4. Python Program to Check Prime Number
  5. Reflection in Java - Getting Class Information
  6. Serialization Proxy Pattern in Java
  7. this Keyword in Java With Examples
  8. Difference Between Two Dates in Java