Variable Length Arguments ( Args), Keyword Varargs ( Kwargs) in Python
Variable Length Arguments ( Args), Keyword Varargs ( Kwargs) in Python
Variable Length Arguments ( Args), Keyword Varargs ( Kwargs) in Python
In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols:
1.) *args
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key
worded, variable-length argument list.
The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of
extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
For example : we want to make a multiply function that takes any number of arguments and able to multiply them all together. It can be done using
*args.
Using the *, the variable that we associate with the * becomes an iterable meaning you can do things like iterate over it, run some higher-order
functions such as map and filter, etc.
python3
def myFun(*argv):
print (arg)
Output:
Hello
Welcome
to
GeeksforGeeks
Python3
# Python program to illustrate
Output:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks
2.)**kwargs
The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with
the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).
A keyword argument is where you provide a name to the variable as you pass it into the function.
One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over
the kwargs there doesn’t seem to be any order in which they were printed out.
Example for usage of **kwargs:
python
def myFun(**kwargs):
# Driver code
Output:
last == Geeks
mid == for
first == Geeks
python
# Python program to illustrate **kwargs for
# Driver code
Output:
last == Geeks
mid == for
first == Geeks
Using *args and **kwargs to call a function
Example:
python3
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
myFun(*args)
myFun(**kwargs)
Output:
arg1: Geeks
arg2: for
arg3: Geeks
arg1: Geeks
arg2: for
arg3: Geeks
Using *args and **kwargs in same line to call a function
Example:
python3
def myFun(*args,**kwargs):
myFun('geeks','for','geeks',first="Geeks",mid=
"for",last="Geeks")
Output:
args: ('geeks', 'for', 'geeks')
kwargs {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}
V ariable arg uments help in the scenario whe re the e xact numb er o f argum ents are not known in the
be ginn ing , it also hel ps to make your funct ion mo re flexib le . Consi der the scenari o wh ere you h ave a fu nction
to ad d numb ers .
This funct ion can only be used to add t wo numb ers , i f you pass more th an t wo numbe rs you wil l 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
B y ch anging the argu ment to *arg s you c an spec ify th at fun ction accepts vari ab le num ber of argu ments and
c an be used to sum ‘n ’ nu mbe rs.
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
1. It is not m and atory to n ame variabl e lengt h argum ent as ‘*arg s’. What is re qui red i s *, variable name
c an be an y variable name fo r exam ple *n umbe rs , *n ames .
2. Using variabl e lengt h argume nt you can p ass ze ro or more arg ument s to a funct ion .
3. V alues pass to * args are sto red in a tuple .
4. Be fo re variabl e args you can h ave a fo rm al argument but not aft er a vari ab le arg s. A fter variab le
arg ument you can have ke yword arg uments .
5. def add_num(n, *numbers):
6. sum = 0
7. print('n is', n)
8. for num in numbers:
9. sum += num
10. sum += n
11. return sum
12.
13. result = add_num(8, 5, 6, 7)
print('Sum is', result)
Output
n is 8
Sum is 26
As you can see here n i s a fo rm al arg ument and first value is pas sed to that arg ument .
I f you chang e the funct ion to have a formal argu ment afte r the vari ab le length argument -
Output
result = add_num(8, 5, 6, 7)
TypeError : add_num() missing 1 required keyword -only argument : 'n'
Output
n is 8
Sum is 26
Keyword variable length arguments in Python
Pyt hon ke yword vari ab le len gth argu ment is an argum ent that accept variabl e num ber of keywo rd argume nts
(argu ments in the form of key, value p ai r). To ind ic ate that the functi on can t ake ke yword variabl e len gth
arg ument you write an arg ument using do uble aste ris k ‘** ’, fo r e xampl e **kwarg s.
V alues pass ed as keywo rd variabl e length argume nt are store d in a d iction ary that is refere nced b y the
keywo rd arg name.
Output
Firstname = Jack
Lastname = Douglas
marks1 = 45
marks2 = 42
Firstname = Lisa
Lastname = Montana
marks1 = 48
marks2 = 45
marks3 = 49
You can pass a formal argu ment be fore a keywo rd vari ab le l ength arg ument but not afte r th at so fol lowin g is
a valid funct ion de finitio n.
def function2():
print("x in function2=", x)
function1()
function2()
#scope here too
print('x=', x)
Output
x in function1= 10
y in function1= 7
x in function2= 10
x= 10
In the example variable x is declared outside any function so it’s scope is global. This global variable x can be accessed inside the
functions as well as outside the functions (as done in last print statement).
If we modify the above example a bit and bring variable x with in the function1() then you will get an error as x won’t
be visible in function2() or outside any function.
def function1():
x = 10
y = 7
print("x in function1=", x)
print("y in function1=", y)
def function2():
print("x in function2=", x)
function1()
function2()
# no scope here
print('x=', x)
output
x in function1= 10
y in function1= 7
File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 12, in <module>
function2()
File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 9, in function2
print("x in function2=", x)
NameError: name 'x' is not defined
global keyword in Python
As we have learned till now a variable declared outside any function has a global scope where as a variable
declared inside any function has a local scope. If you declare a variable inside a function having the same
name as the global variable then with in the scope of the method local variable overshadows the global
variable.
x = 10
def function():
#local var
x = 12
print("x in function=", x)
function()
# Outside function
print('x=', x)
Output
x in function= 12
x= 10
As you can see here inside function() x has the value 12 even if there is a global variable x with value 10.
Now consider the scenario where you want to modify the global variable itself inside a function. You will get
an error ‘local variable 'x' referenced before assignment’ because Python looks for x declaration with in the
function which is not found thus the error.
x = 10
def function():
x = x + 1
print("x in function=", x)
function()
# Outside function
print('x=', x)
Output
x = 10
def function():
# to access global variable
global x
x = x + 1
print("x in function=", x)
function()
# Outside function
print('x=', x)
Output
x in function= 11
x= 11
x = 0
y = ""
In another module (Display.py) Test.py is imported and values are assigned to the variables that are declared in Test.py.
import Test
def display():
#assigning values to global variables
Test.x = 7
Test.y = "Module"
print('x=',Test.x, 'y=', Test.y)
Then you can import these modules and display values of the variables directly or by calling the function display of Display.py module.
import Display
import Test
Display.display()
print(Test.x)
print(Test.y)
Output
x= 7 y= Module
7
Module
In the example there is a function myfunction() where a variable count is declared. In the nested function increment() value of count is
incremented. This results in an error ‘UnboundLocalError: local variable 'count' referenced before assignment’ because count variable is in
the scope of outer method.
def myfunction():
count = 0
#nested function
def increment():
count += 1
return count
# calling nested function
print('count is-', increment())
print('count is-', increment())
print('count is-', increment())
myfunction()
Output
To ensure that nested function has access to the variable in the enclosing scope, you can use nonlocal keyword with variable in the body
of nested function.
def myfunction():
count = 0
def increment():
nonlocal count
count += 1
return count
# calling nested function
print('count is-', increment())
print('count is-', increment())
print('count is-', increment())
myfunction()
Output
count is- 1
count is- 2
count is- 3
Pyt hon nonlo cal ke yword is used with variabl es in nest ed fu nction s to b ind the variabl e de fine d in oute r
functio n, b y m aking vari ab le non local it can be acce ssed in nested functio n.
In the e xample there is a fu nction m yfu nction () with a vari ab le x define d in it an d there is a neste d
functio n infunction() with a vari ab le x define d wi th in its scope .
def myfunction():
x = 7
def infunction():
x = 20
print ('x inside infunction' , x)
infunction()
print ('x inside myfunction' , x)
myfunction()
Output
x inside infunction 20
x inside myfunction 7
As you can see value of x is printed as per the scope it i s defined in.
No w, consider the scenari o wh ere you wan t to acces s the vari ab le de fi ned in outer functio n. You may th ink of
us ing g lobal keywo rd to access vari ab le in glob al sco pe but the p robl em is e ven the oute r fu nction variab le is
not dee med g lob al as it is wi th in a local scope of a functio n.
def myfunction():
x = 7
def infunction():
global x
x = 20
print ('x inside infunction' , x)
infunction()
print ('x inside myfunction' , x)
myfunction()
Output
x inside infunction 20
x inside myfunction 7
As you can see usin g glob al ke yword does n’t help i n this scen ario .
def myfunction():
x = 7
def infunction():
nonlocal x
x = 20
print ('x inside infunction' , x)
infunction()
print ('x inside myfunction' , x)
myfunction()
Output
x inside infunction 20
x inside myfunction 20
As you can see now nested functi on is ac cessi ng the x defined in the outer scope.
Here note that though nonloc al keywo rd is use d to refer to p reviou sly boun d vari ab les in the nearest
enc losing scope , but it do es exclud e glob al .
x = 10
def myfunction():
x = 7
def infunction():
nonlocal x
x = 20
print ('x inside infunction' , x)
infunction()
print ('x inside myfunction' , x)
myfunction()
print ('x in global scope' , x )
Output
x inside infunction 20
x inside myfunction 20
x in global scope 10
When you want to use a global variable inside a function you can qualify a variable with global keyword
inside the function body.
For example-
def myfunction():
global x
.....
.....
Using global keyword in Python
The third point mentioned above “If you declare a variable inside a function having the same name as the
global variable then with in the scope of the method local variable overshadows the global variable.” is the
basis for using global keyword in Python. To understand it let’s go through few scenarios.
#global variable
x = 10
def myfunction():
# local variable
x = 7
print('x inside function', x)
myfunction()
print('x outside function', x)
Output
x inside function 7
x outside function 10
As you can see local variable x inside the function overshadows the global variable x with in the limit of the
function. Outside the function scope changes to global variable.
You may have a scenario where you’d want to modify global variable with in a function.
#global variable
x = 10
def myfunction():
#modify global variable
x = x+2
print('x inside function', x)
myfunction()
print('x outside function', x)
Output
As you can see trying to modify global variable with in the function results in an error ‘UnboundLocalError: local
variable 'x' referenced before assignment’ because Python looks for variable x with in the function which is not found
thus the error.
If you want to modify global variable inside a function then the variable needs to be declared using global keyword with in the function.
That way you can modify global variable with in the local context.
#global variable
x = 10
def myfunction():
global x
#modify global variable
x = x+2
print('x inside function', x)
myfunction()
print('x outside function', x)
Output
x inside function 12
x outside function 12
As you can see now global variable can be changed with in the function.
By qualifying a variable with global keyword inside a function you can create a global variable inside a function that can be used outside
the function too.
def myfunction():
# global variable from local scope
global x
x = 7
print('x inside function', x)
myfunction()
print('x outside function', x)
Output
x inside function 7
x outside function 7