Source

*args and **kwargs in python explained

Hi there folks. I have come to see that most new python programmers have a hard time figuring out the *args and **kwargs magic variables. So what are they? First of all let me tell you that it is not necessary to write *args or **kwargs. Only the * (aesteric) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention. So now lets take a look at *args first.

Usage of *args

*args and **kwargs are mostly used in function definitions. *args and **kwargs allow you to pass a variable number of arguments to a function. What does variable mean here is that you do not know before hand that how many arguments can be passed to your function by the user so in this case you use these two keywords. *args is used to send a non-keyworded variable length argument list to the function. Here’s an example to help you get a clear idea:

def test_var_args(f_arg, *argv):
    print "first normal arg:", f_arg
    for arg in argv:
        print "another arg through *argv :", arg

test_var_args('yasoob','python','eggs','test')

This produces the following result:

first normal arg: yasoob
another arg through *argv : python
another arg through *argv : eggs
another arg through *argv : test

I hope this cleared away any confusion that you had. So now lets talk about **kwargs

Usage of **kwargs

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function. Here is an example to get you going with it:

def greet_me(**kwargs):
    if kwargs is not None:
        for key, value in kwargs.iteritems():
            print "%s == %s" %(key,value)
 
>>> greet_me(name="yasoob")
name == yasoob

So can you see how we handled a keyworded argument list in our function. This is just the basics of **kwargs and you can see how useful it is. Now lets talk about how you can use *args and **kwargs to call a function with a list or dictionary of arguments.

Using *args and **kwargs to call a function

So here we will see how to call a function using *args and **kwargs. Just consider that you have this little function:

def test_args_kwargs(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

Now you can use *args or **kwargs to pass arguments to this little function. Here’s how to do it:

# first with *args
>>> args = ("two", 3,5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

Order of using *args, **kwargs and formal args

So if you want to use all three of these in functions then the order is

some_func(fargs,*args,**kwargs)

I hope you have understood the usage of *args and **kwargs. If you have got any problems or confusions with this then feel free to comment below. For further study i suggest the official python docs on defining functions and *args and **kwargs on stackoverflow.

You might also like:

Newsletter

×

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments

R-M-R

Saw your links to this in the python programmers group on fb. I have been coding for a while now, but didn’t know anything about this. your blog is really really helpful! Thank’s for posting this, and keep the fb group updated with your posts!

Yasoob
In reply to R-M-R

Thanx i am glad that you found this helpful. If you want regular updates then consider following this blog. The link for following is available in the menu.

Nit

Ahhh thanks :)

Yasoob
In reply to Nit

No problem , cheers

Terrence Andrew Davis

U0 PrintF(U8 *fmt,…) { //like “this” in C++, in HolyC argv[] and argc }

Amino Prime

Great article, exactly what I needed.

raghvendra

Thanks for nice explanation.

Yasoob
In reply to raghvendra

No problem……I am glad that i could help you guys.

Xavi

I am definly going to follow this blog

Per

Hi im trying to use a fill_between command but i dont know what to put in the **kwargs “section”.

This is my coding:

(…)

fill_between(x, y1, y2=0, where=None, **kwargs)

What should i write in the kwargs** section?

Greetings from Norway.

Yasoob
In reply to Per

Hi Per. Welcome to my blog. Now regarding your problem I am sorry that I am not able to clearly understand you. What you can do is that you can write a detailed email to me or use stackoverflow :) In both cases you will get help.

Mahan Marwat
In reply to Per

The thingy **kwargs by itself and then refer to them in your function as kwargs.

Juan Sierra Pons

Quick and easy. Still learning python from a book and I didn’t find anything on it reletated to to *args and *kwargs Thanks for sharing your knowlegde and time.

Yasoob
In reply to Juan Sierra Pons

I am glad you liked it :)

Mahesh Puttanna

hi really it’s I needed, I searched a lot finally I found and I understand *args and **kwargs. can you please in the same way explain django views modesls program and urls patterens mapping.thank you very much.

Yasoob
In reply to Mahesh Puttanna

Hi Mahesh I am glad that you liked the post. I will consider writing on django views in the future.

Deepak Devanand

Very helpful. Thank you Yasoob.

Scooper

“bite sized” is written “bite-sized”, btw…

Rohit shukla

thnx dear yasoob a great article

Rohit shukla

will u also explain about a library storm

parkerandhobbes

Thank you! It’s the best explanation I’ve read but I don’t really see the point in them.

In PHP we just pass variables onto functions. A variable can be well… anything. A number, a string, an array or even a multidimensional array - can all be handled by just saying:

function hello($some_variable) { //do some stuff }

In PHP the function doesn’t really care what gets passed to it. Whether you through into the function, PHP will deal with it. So, if PHP is able to live quite happily without args and kwargs, how come Python seems to have a problem here?

This is not a loaded question. It’s a sincere question from a dude who is trying to learn. Perhaps I’m missing something.

Many thanks,

-DC

Mahan Marwat
In reply to parkerandhobbes

Python is dynamically typed language. Python functions really doesn’t care about what you pass to them. But you got it the wrong way… please re-read the post. If you want to pass one thousand arguments to your function, then you can’t explicitly define every parameter in your function definition. For the reason you will use *args and your function will be automagically able to handle all the arguments you pass to them for you.

Sumer Sadawarti

Awesome…. doubt cleared… thanks a lot.. :)

Notice one thing: **kwargs arrange keys in alphabetical order e.g:

def print_it(f_arg, **kwargs): print f_arg for key,value in kwargs.iteritems(): print “%s=%s”%(key,value)

print_it(‘sumer’,name=‘panda’,age=12)

output:

sumer age=12 name=panda

‘age’ gets printed before ‘name’

once again….this post helped me a lot…. thanks dude.

ko_dong_sung

thank you so much easy explanations.

Ivo

The best explanation about *args and **kwargs I have ever seen. Thank you a lot.

Falon

For Python3 now please note a difference: in the first example for usage of **kwargs the line that has this: for key, value in kwargs.iteritems():

gave me an error because it needs to be: for key, value in kwargs.items():

since iteritems() no longer is defined in Python3 because items() can do the same thing.

glayn

OMG you r like the best teacher EVER! thnx a bunch

niteDrain

In the second paragraph, you’ve said:

“*args is used to send a non-keyworded variable length argument list to the function”.

As far as I understand, what you’re passing is any number of non-keyworded arguments in the function call. But NOT in a list. Am I wrong?

Thanks for the article : )

shengy90

Reblogged this on codaborate.

alnauto

That was a short but insightful explanation. Thank you very much, I’m sure I can make good use of *args and *kwargs in my future coding!

alnauto

That was a short but insightful explanation. Thank you very much, I’m sure I can make good use of *args and **kwargs in my future coding!

Yasoob
In reply to alnauto

I am glad that it helped!

Edd

Well, this was quite nice. now I know how to use *args and **kwargs correctly. If’s easier thant what I thought before. Thank you for the tips.

vu2aeo

Excellent tutorial. Thanks a lot!

Jay

When using **kwargs, we call those ‘keyword’ arguments. But in Python, I thought ‘keyword’ referred to Python keywords like ‘if’, ‘else’, ‘while’, ‘for’, etc. I’m guessing the term ‘keyword’ means two completely different things depending on the context (Python language keywords vs. keyword arguments) but I wasn’t sure, can someone clarify?

durexyl

just a minor (and late) correction: * is not “aesteric”, but “asterisk” :)

Muneer

Nice. Very usefull.

Mohammed Reda Berrohou

Wonderful explaining Thank You Very very much

Aditya

I have one doubt on kwarg.pop(). What is the use of this method? I am bit confused on this. Can you please explain it to me?

Luiz Rodrigo

Nice explanation :D , thanks

Harshitha Dinesh

Very well explained. Thank you :)

Ritesh Kumar

Awesome…Thanks for Nice explanation..This is what i was looking for!

celinedebeauvoir

Thank you, awesome explanation and very noble of you to teach the public :)

dvigneshwer

Reblogged this on Vigneshwer Dhinakaran and commented: Learn to play with *args and *kwargs

Joseph Vithayathil

Thank you for the wonderful simple and neat documentation on the topic.

Alexey Z

I hope this doesn’t add too much confusion, but I wanted to note that in the most general case, Python allows all 4 forms of passing arguments used together:

>>> def f(a1, *args, a2=2, **kwargs): print(a1, args, a2, kwargs)

we’ve defined function f that takes a1 as a positional argument, args as a collection of any number of additional positional arguments, a2 as a keyworded argument, and finally kwargs as an arbitrary dict of other keyworded arguments

At a minimum, we have to supply a1 argument. Note that args and kwargs are not None, but are just empty tuple and dict, respectively

>>> f(1) 1 () 2 {}

Now let’s try specifying everything

>>> f(1, 2, 3, a2=20, a3=30, a4=40) 1 (2, 3) 20 {‘a4’: 40, ‘a3’: 30}

We can pass in all arguments by unrolling a tuple and a dict at the call site

>>> f(1, *(2,), a2=20, **{‘a3’: 30, ‘a4’: 40}) 1 (2,) 20 {‘a4’: 40, ‘a3’: 30}

Notice how we can override a2 without using standard keyworded argument syntax and how it does not appear in kwargs inside the function itself

>>> f(1, *(2,), **{‘a3’: 30, ‘a4’: 40, ‘a2’: 666}) 1 (2,) 666 {‘a4’: 40, ‘a3’: 30}

eruca

I have a question: >>> def run_with_func(func, *args): … return func(*args) >>> def sum_args(*args): … return sum(args)

can you indicate the situation when to use *args, when to use args,

Maxx
In reply to eruca

How about like this:

def sum_args(*numbers): summ=0 for arg in numbers: summ = summ + arg return summ >>> sum_args(1,2,3,4,5) 15

Rommel Rodriguez Perez

Great article, thanks!.

airwavves

Cleared things up for and didn’t waste my time.

Vanen Dallas

Awesome! Thank you for explaining this with such clarity

Vicente

¡Magnificent!

nkem

thanks. I appreciate your clear explanations

do.OJi (@beltreg)

Thank you. Great post.

Robery Davis

Very clear and well written article. It cleared up the mystery for me even though I have been dabbling in python for 17 years. Much better written then the official documentation explanation. And that was because it was written in Plain English and NOT geekese.

mmagic

I like your explanation style, makes a convoluted but simple features of Python, simple to understand for normal human. This should be inside the official python documentation.

jayeoba sunmola

Great article, thanks!

Alex

Great job, I can see that this article is 10 years old as i write this, good to see that the basics never get old. Thanks for taking your time to explain the concept. I know understand fully how to use *args and *kwargs. Great content.

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK