Python variable arguments keyword

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

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)
Sum is 18 Sum is 26 Sum is 35
  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)

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-

Then it results in an error.

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)

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)
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!

Источник

Python Function Arguments – Default, Keyword and Arbitrary

In this tutorial, we will discuss variable function arguments. In the previous tutorials of Python function and Python user defined functions we learned that we call the function with fixed number of arguments, for example if we have defined a function to accept two arguments, we have to pass the two arguments while calling the function. Here we will see how to call the function with variable arguments using Default, Keyword and Arbitrary arguments.

Table of Contents

Fixed positional function arguments

Before we discuss variable function arguments let’s see the errors we get when we call the function with variable arguments without using Default, Keyword and Arbitrary arguments.

Here we have defined a function demo() with two parameters name and age , which means this function can accept two arguments while we are calling it.

def demo(name,age): """This function displays the age of a person""" print(name + " is " + age + " years old") # calling the function demo("Mohan","20")

Python Function Arguments

Output:

Let’s see what happens we call this function with variable number of arguments:
Here we are calling the function demo() with a single argument, as you can see in the output that we got an error.

def demo(name,age): print(name + " is " + age + " years old") # calling the function demo("Mohan")
TypeError: demo() missing 1 required positional argument: 'age'

Here we are calling the function with no arguments and we are getting an error.

def demo(name,age): print(name + " is " + age + " years old") # calling the function demo()
TypeError: demo() missing 2 required positional arguments: 'name' and 'age'

Variable Function Arguments in Python

Till now we have seen the fixed function arguments in Python. We have also learned that when we try to pass the variable arguments while calling a function, we get an error.

Now it’s time to learn how to pass variable arguments in function using Default, Keyword and Arbitrary arguments.

Python Default Arguments

We can provide default values to the function arguments. Once we provide a default value to a function argument, the argument becomes optional during the function call, which means it is not mandatory to pass that argument during function call. Let’s take an example to understand this concept.

Here in this example, we have provided the default value to the parameter age using the assignment (=) operator.

In the following example parameter name doesn’t have a default value, so it is mandatory during function call. On the other hand, the parameter age has a default value, so it is optional during a function call.

Note:
1. If you provide a value to the default argument during a function call, it overrides the default value. For example, in the following program we have overriden the age of Lucy & Bucky to 20 & 40 respectively.

2. A function can have any number of default arguments, however if an argument is set to be a default, all the arguments to its right must always be default. For example, def demo(name = “Mohan”, age): would throw an error (SyntaxError: non-default argument follows default argument) because name is a default argument so all the arguments that are following it, must always be default.

def demo(name, age = "30"): """ This function displays the name and age of a person If age is not provided, it's default value 30 would be displayed. """ print(name + " is " + age + " years old") demo("Steve") demo("Lucy", "20") demo("Bucky", "40")

Python Default Argument

Output:

Python Keyword Arguments

We have learned that when we pass the values during function call, they are assigned to the respective arguments according to their position. For example if a function is defined like this: def demo(name, age): and we are calling the function like this: demo(«Steve», «35») then the value “Steve” is assigned to the argument name and the value “35” is assigned to the argument age . Such arguments are called positional arguments.

Python allows us to pass the arguments in non-positional manner using keyword arguments. Lets take an example to understand this:

def demo(name, age): print(name + " is " + age + " years old") # 2 keyword arguments (In order) demo(name = "Steve", age = "35") # 2 keyword arguments (Not in order) demo(age = "20", name = "Mohan") # 1 positional and 1 keyword argument demo("Bucky", age = "40")

Python Keyword Arguments

Output:

Note: In the above example, during third function call demo(“Bucky”, age = “40”) we have keyword argument and non-keyword argument. In the example keyword argument follows (is after) the non-keyword argument. However if you try to place the keyword argument before the non-keyword argument, it would throw the following error:

SyntaxError: non-keyword arg after keyword arg

So please keep this in mind that when you are mixing the positional and keyword arguments, the keyword argument must always be after the non-keyword argument (positional argument).

Python Arbitrary Arguments

Python allows us to have the arbitrary number of arguments. This is especially useful when we are not sure in the advance that how many arguments, the function would require.

We define the arbitrary arguments while defining a function using the asterisk (*) sign.

def fruits(*fnames): """This function displays the fruit names""" # fnames is a tuple with arguments for fruit in fnames: print(fruit) fruits("Orange","Banana","Apple","Grapes")

Python Arbitrary Arguments

Output:

In the above example we are using the * before the parameter fnames that allows us to accept the arbitrary number of arguments during function call.

All the passed arguments are stored in as a tuple, before they are passed to the function. Inside the function, we are displaying all the passed arguments using for loop.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Читайте также:  Java вызвать конструктор предка
Оцените статью