Variable Length Arguments ( Args), Keyword Varargs ( Kwargs) in Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

*args and **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:

Special Symbols Used for passing arguments:-


1.)*args (Non-Keyword Arguments)
2.)**kwargs (Keyword Arguments)
Note: “We use the “wildcard” or “*” notation like this – *args OR **kwargs – as our function’s argument when we have doubts about the number of
arguments we should pass in a function.” 

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

# Python program to illustrate 

# *args for variable number of arguments

def myFun(*argv):

    for arg in argv:

        print (arg)

   

myFun('Hello', 'Welcome', 'to',


'GeeksforGeeks')

Output: 
Hello
Welcome
to
GeeksforGeeks
 

 Python3
# Python program to illustrate

# *args with first extra argument

def myFun(arg1, *argv):

    print ("First argument :", arg1)

    for arg in argv:

        print("Next argument through *argv :", arg) 

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

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

# Python program to illustrate 

# *kwargs for variable number of keyword arguments 

def myFun(**kwargs):

    for key, value in kwargs.items():

        print ("%s == %s" %(key, value)) 

# Driver code

myFun(first ='Geeks', mid ='for', last='Geeks')   

Output: 
last == Geeks
mid == for
first == Geeks
 

 python
# Python program to illustrate  **kwargs for

# variable number of keyword arguments with

# one extra argument. 

def myFun(arg1, **kwargs):

    for key, value in kwargs.items():

        print ("%s == %s" %(key, value)) 

# Driver code

myFun("Hi", first ='Geeks', mid ='for', last='Geeks')   

Output: 
last == Geeks
mid == for
first == Geeks
 
Using *args and **kwargs to call a function
Example:
 

 python3

def myFun(arg1, arg2, arg3):

    print("arg1:", arg1)

    print("arg2:", arg2)

    print("arg3:", arg3)

     

# Now we can use *args or **kwargs to

# pass arguments to this function :

args = ("Geeks", "for", "Geeks")

myFun(*args) 

kwargs = {"arg1" : "Geeks", "arg2" : "for",


"arg3" : "Geeks"}

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

    print("args: ", args)

    print("kwargs: ", kwargs) 

# Now we can use both *args ,**kwargs

# to pass arguments to this function :

myFun('geeks','for','geeks',first="Geeks",mid=
"for",last="Geeks")

Output: 
args: ('geeks', 'for', 'geeks')
kwargs {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}

Variable length arguments in Python


A variable lengt h argume nt as the name sug gests is an argu ment that c an  acce pt vari ab le nu mbe r of values .
To ind icat e that the functio n can take vari ab le num ber of argu ment you writ e a variabl e argum ent usin g a ‘*’,
for e xamp le *args .

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 .

def add_num (num1, num2):


return num1 + num2

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.

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 len gth argu ments in Pyt hon-

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 -

def add_num (* numbers, n ):

Then it result s in an e rror.

Output

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

You can pass a ke yword arg ument afte r variabl e 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
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.

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 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 display_records (a, ** records):

Global variable in Python


Variables that are declared outside a function are known as global variables in Python. These variables have a greater scope and are
available to all the functions that are defined after the declaration of global variable.

Python global variable example


#global variable
x = 10
def function1():
y = 7
print("x in function1=", x)
print("y in function1=", y)

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

Local variable in Python


When a variable is declared inside a function then it is a local variable. A local variable’s scope is limited with in the
function where it is created which means it is available with in the function where it is declared not outside that
function.

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

File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 6, in <module>


function()
File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 3, in function
x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

Python global keyword example


In such scenario, where you want to use the global variable inside a function, you can use global keyword with the variable in the start
of the function body.

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

Sharing global variables in multiple Python modules


Global variables in Python can be shared across multiple modules. In the example there is a module Test.py that declares two variables.

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

Non-local variables in Python


Non-local variables are created using nonlocal keyword in Python. The nonlocal keyword causes the variable to refer to previously bound
variables in the nearest enclosing scope excluding globals.

nonlocal keyword is added in Python 3.

Python nonlocal keyword example


nonlocal keyword is used with variables in nested functions where the variable is in outer scope, by making variable nonlocal it can be
accessed in nested function. Let’s clarify it with an example.

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

File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 12, in <module>


myfunction()
File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 8, in myfunction
print('count is-', increment())
File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 5, in increment
count += 1
UnboundLocalError: local variable 'count' referenced before assignment

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

Python nonlocal keyword


The nonlocal ke yword c auses the vari ab le to re fe r to pre vi ousl y bo und variabl es in the ne arest enclo sing
sco pe exclud ing glob als . Note th at nonloc al ke yword is adde d in Pytho n 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.

Let ’s try to und erst and it wi th some e xamp les.

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 .

Using nonlocal keyword


In the scen ario whe re you want to ac cess the variabl e define d in oute r funct ion with in the nested funct ion
you can use nonloc al ke yword in Pyt hon to re fer to pre vi ousl y bou nd variabl es in the ne are st enclos ing sco pe.

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

Python global keyword

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.

Variable with same name in both global and local scope

#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.

Modifying global variable with in a function

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

File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 8, in <module>


myfunction()
File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 5, in myfunction
x = x+2
UnboundLocalError: local variable 'x' referenced before assignment

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.

Examples using global keyword in Python


So we have seen the scenarios where trying to access global variable with in the method is required and that’s where Python global
keyword is used.

Modifying global variable with in a function

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.

Creating a global variable from a local scope

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy