The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:

>>> def print_everything(*args):
        for count, thing in enumerate(args):
...         print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage

Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:

>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:

def table_things(titlestring, **kwargs)

You can also use both in the same function definition but *args must occur before **kwargs.

You can also use the * and ** syntax when calling a function. For example:

>>> def print_three_things(a, b, c):
...     print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat

As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.

Answer from David Webb on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-args-and-kwargs-in-python-3
How To Use *args and **kwargs in Python 3 | DigitalOcean
3 weeks ago - Python functions accept positional arguments (matched by position) and keyword arguments (matched by name). Variable-length argument lists are handled by *args and **kwargs, which collect any extra positional or keyword arguments into a single parameter. You write a function that adds two numbers.
🌐
W3Schools
w3schools.com › python › python_args_kwargs.asp
Python *args and **kwargs
def my_function(*numbers): if ... of arguments and can access the items accordingly: Using **kwargs to accept any number of keyword arguments:...
Discussions

python - Use of *args and **kwargs - Stack Overflow
Note that *args/**kwargs is part of function-calling syntax, and not really an operator. This has a particular side effect that I ran into, which is that you can't use *args expansion with the print statement, since print is not a function. ... Unfortunately it doesn't compile (syntax error). ... But prints the arguments as a tuple, which isn't what we want. ... print is a function in Python3:) docs.python.org/3... More on stackoverflow.com
🌐 stackoverflow.com
default value - Proper way to use **kwargs in Python - Stack Overflow
Indeed, in Python 3 you can even have keyword-only arguments that aren't optional (ones without a default value). However, Python 2 still has long years of productive life ahead, so it's better to not forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3! ... @Alex Martelli: I haven't found a single answer that claims kwargs ... More on stackoverflow.com
🌐 stackoverflow.com
What are args** and kwargs** and __somethinghere__ in python?
Some reading More on reddit.com
🌐 r/learnpython
18
67
October 15, 2024
What are *args and **kwargs ?
Functions take arguments, sometimes you want to be able to pass a dynamic amount of arguments or different arguments - for example a function that adds all arguments passed to it - that's where *args and **kwargs come in. *args is used for passing positional arguments, **kwargs is used for passing keyword arguments. So, if you wanted to write the aforementioned function with *args you would write: def add(*args): return sum(args) #add(1,2,3,4) #10 or to better illustrate what's going on def read_args(*args): for arg in args: print(arg) #read_args(1,2,3,4) #1 #2 #3 #4 The same applies to **kwargs. The important thing to understand here is what's really going on under the hood: passing *args just creates a tuple from all of the positional arguments you pass it, once you understand that, manipulating the arguments is easy. So passing add(1,2,3,4) just means that you end up with a property args with the value of (1,2,3,4). And with kwargs it just converts all of the dynamic keyword arguments you've passed into a dictionary. Meaning passing read_kwargs(one=1, two=2) just leaves you with a property of type dictionary that equals {'one': 1, 'two': 2}. Also an important sidenote is that the keywords args and kwargs isn't important technically - you can name them anything you'd like, the only thing that python is concerned with is the *. Though always use the arg/kwarg as it's convention that's universal at this point. More on reddit.com
🌐 r/learnpython
18
127
November 18, 2017
🌐
Real Python
realpython.com › python-kwargs-and-args
Python args and kwargs: Demystified – Real Python
November 7, 2023 - $ python change_tuple.py Traceback (most recent call last): File "change_tuple.py", line 3, in <module> my_tuple[0] = 9 TypeError: 'tuple' object does not support item assignment · This is because a tuple is an immutable object, and its values cannot be changed after assignment. Keep this in mind when you’re working with tuples and *args. Okay, now you’ve understood what *args is for, but what about **kwargs?
🌐
Python Tips
book.pythontips.com › en › latest › args_and_kwargs.html
1. *args and **kwargs — Python Tips 0.1 documentation
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
🌐
Programiz
programiz.com › python-programming › args-and-kwargs
Python *args and **kwargs (With Examples)
Python passes variable length non keyword argument to function using *args but we cannot use this to pass keyword argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of keyword arguments to the function.
🌐
GeeksforGeeks
geeksforgeeks.org › args-kwargs-python
*args and **kwargs in Python - GeeksforGeeks
In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs.
Published   December 11, 2024
Top answer
1 of 11
1828

The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:

>>> def print_everything(*args):
        for count, thing in enumerate(args):
...         print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage

Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:

>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:

def table_things(titlestring, **kwargs)

You can also use both in the same function definition but *args must occur before **kwargs.

You can also use the * and ** syntax when calling a function. For example:

>>> def print_three_things(a, b, c):
...     print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat

As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.

2 of 11
522

One place where the use of *args and **kwargs is quite useful is for subclassing.

class Foo(object):
    def __init__(self, value1, value2):
        # do something with the values
        print value1, value2

class MyFoo(Foo):
    def __init__(self, *args, **kwargs):
        # do something else, don't care about the args
        print 'myfoo'
        super(MyFoo, self).__init__(*args, **kwargs)

This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.

Find elsewhere
🌐
W3Schools
w3schools.com › python › gloss_python_function_arbitrary_keyword_arguments.asp
Python **kwargs
Python Examples Python Compiler ... arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition....
Top answer
1 of 14
650

You can pass a default value to get() for keys that are not in the dictionary:

self.val2 = kwargs.get('val2',"default value")

However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place?

def __init__(self, val2="default value", **kwargs):
2 of 14
310

While most answers are saying that, e.g.,

def f(**kwargs):
    foo = kwargs.pop('foo')
    bar = kwargs.pop('bar')
    ...etc...

is "the same as"

def f(foo=None, bar=None, **kwargs):
    ...etc...

this is not true. In the latter case, f can be called as f(23, 42), while the former case accepts named arguments only -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- threading.Thread is an example. The first form is how you implement that in Python 2.

The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single * in the def signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:

def f(*, foo=None, bar=None, **kwargs):
    ...etc...

Indeed, in Python 3 you can even have keyword-only arguments that aren't optional (ones without a default value).

However, Python 2 still has long years of productive life ahead, so it's better to not forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!

🌐
CloudSigma
blog.cloudsigma.com › home › customers › using *args and **kwargs parameters in your code: a python 3 tutorial
Using *args and **kwargs Parameters in your Code: a Python 3 Tutorial • CloudSigma
June 28, 2022 - Observe the output when you run the program using the python some_args.py command: It is possible to change the program to an iterable list data type as well with a different variable as a name. The following code combines *args with a named parameter: ... On the other hand, you can apply keyworded arguments with **kwargs. Make sure to create a variable that is equal to a dictionary. It should have 2 key-value pairs. Here is how we will pass the variable to a function with 3 arguments:
🌐
freeCodeCamp
freecodecamp.org › news › args-and-kwargs-in-python
How to Use *args and **kwargs in Python
March 23, 2022 - In this case it's **numbers**. But it's generally a standard way to use ***args** as the name. `kwargs** allows us to pass a variable number of keyword arguments to a Python function.
🌐
WsCube Tech
wscubetech.com › resources › python › args-and-kwargs
Python *args and **kwargs (With Example)
November 5, 2025 - Learn about Python *args and **kwargs with examples. Understand how to use these flexible arguments to write more dynamic and reusable functions.
🌐
Towards Data Science
towardsdatascience.com › home › latest › 10 examples to master *args and **kwargs in python
10 Examples to Master *args and **kwargs in Python | Towards Data Science
January 20, 2025 - Since the default value is True, the function returns the sum of the arguments unless option parameter is declared as False. ... The *kwargs collect all the keyword arguments that are not explicitly defined.
🌐
Reddit
reddit.com › r/learnpython › what are args** and kwargs** and __somethinghere__ in python?
r/learnpython on Reddit: What are args** and kwargs** and __somethinghere__ in python?
October 15, 2024 -

Hello everyone, I hope you all are doing well. I’m confused about these keywords in Python and what they do and where I can use them, since am new to python.

Anyone?

Top answer
1 of 10
75
Some reading
2 of 10
43
Symmetrically double-underscored names ('dunders') like __this__ aren't anything special in and of themselves. This is just a convention used by Python devs to mark things that are 'magic' in some way (usually, other builtin Python things rely on them in some way, e.g. __init__() is called when constructing a class, or __repr__() is called when printing). args and kwargs aren't special either; it's the asterisks (*foo and **bar) that are the magic bits. They are related and are used to make working with call signatures nicer, for either positional or keyword arguments, respectively. Sometimes you're not sure how many parameters a function will need to receive - sometimes it's one, sometimes it's twenty. For example, a function like sum() - you could lock it to only ever adding two numbers, sum(a, b), but that's not super nice for the users - we'd likely prefer to add ALL the numbers someone puts in, right? In more oldschool languages, a canonical solution would be to take some kind of a list of numbers, e.g. sum(numbers), and that works - but now your users have to slap extra braces around things, e.g. sum([1, 2, 3, 4]), which is annoying. Instead, the single-star syntax before an argument in a function signature (in our case, changing sum(numbers) => sum(*numbers)) flags to Python to wrap any positional arguments (that don't look like they belong to an earlier, non-starry arg) into a tuple under the hood. When passing inputs into a function, this is reversed - if you have anything listey and the function expects a bunch of positional arguments (starry or not, doesn't matter), if you put in an asterisk before the list, Python will unpack that into individual positional arguments. Double-star for kwargs does the same, except for named arguments - it implicitly wraps/unwraps dictionaries-and-friends like one-star wraps/unwraps tuples-and-friends.
🌐
Reddit
reddit.com › r/learnpython › what are *args and **kwargs ?
r/learnpython on Reddit: What are *args and **kwargs ?
November 18, 2017 -

I read few explaination but I just understood they are for variable arguments other than this I am confused

Top answer
1 of 5
85
Functions take arguments, sometimes you want to be able to pass a dynamic amount of arguments or different arguments - for example a function that adds all arguments passed to it - that's where *args and **kwargs come in. *args is used for passing positional arguments, **kwargs is used for passing keyword arguments. So, if you wanted to write the aforementioned function with *args you would write: def add(*args): return sum(args) #add(1,2,3,4) #10 or to better illustrate what's going on def read_args(*args): for arg in args: print(arg) #read_args(1,2,3,4) #1 #2 #3 #4 The same applies to **kwargs. The important thing to understand here is what's really going on under the hood: passing *args just creates a tuple from all of the positional arguments you pass it, once you understand that, manipulating the arguments is easy. So passing add(1,2,3,4) just means that you end up with a property args with the value of (1,2,3,4). And with kwargs it just converts all of the dynamic keyword arguments you've passed into a dictionary. Meaning passing read_kwargs(one=1, two=2) just leaves you with a property of type dictionary that equals {'one': 1, 'two': 2}. Also an important sidenote is that the keywords args and kwargs isn't important technically - you can name them anything you'd like, the only thing that python is concerned with is the *. Though always use the arg/kwarg as it's convention that's universal at this point.
2 of 5
32
It looks like http://book.pythontips.com/en/latest/args_and_kwargs.html explains it pretty well to me.
🌐
Note.nkmk.me
note.nkmk.me › home › python
*args and **kwargs in Python (Variable-Length Arguments) | note.nkmk.me
May 12, 2025 - By convention, *args (arguments) and **kwargs (keyword arguments) are commonly used as parameter names, but you can use any name as long as it is prefixed with * or **. The sample code in this article uses *args and **kwargs.
🌐
El Libro De Python
ellibrodepython.com › args-kwargs-python
📙 Args y Kwargs Python | El Libro De Python
def suma(*args): return sum(args) suma(5, 5, 3) #Salida 13 · Con esto resolvemos nuestro problema inicial, en el que necesitábamos un número variable de argumentos. Sin embargo, hay otra forma que nos proporciona además un nombre asociado al argumento, con el uso de **kwargs. La explicamos a continuación. Al igual que en *args, en **kwargs el nombre es una mera convención entre los usuarios de Python.
Top answer
1 of 4
82

You can do that in Python 3.

def func(a,b,*args,kw1=None,**kwargs):

The bare * is only used when you want to specify keyword only arguments without accepting a variable number of positional arguments with *args. You don't use two *s.

To quote from the grammar, in Python 2, you have

parameter_list ::=  (defparameter ",")*
                    (  "*" identifier [, "**" identifier]
                    | "**" identifier
                    | defparameter [","] )

while in Python 3, you have

parameter_list ::=  (defparameter ",")*
                    (  "*" [parameter] ("," defparameter)*
                    [, "**" parameter]
                    | "**" parameter
                    | defparameter [","] )

which includes a provision for additional parameters after the * parameter.

UPDATE:

Latest Python 3 documentation here.

2 of 4
8

If you want to do a mixture of both remember that *args and **kwargs must be the last parameters specified.

def func(arg1,arg2,*args,kw1=None,kw2=None,**kwargs): #Invalid
def func(arg1,arg2,kw1=None,kw2=None,*args,**kwargs): #Valid

The comments seem to be based on mixing up how a function definition is constructed compared to how the arguments provided are assigned back to the parameters specified in the definition.

This is the definition of this function which has 6 parameters. It is called by passing named and unnamed arguments to it in a function call.

For this example... When an argument is named when calling the function it can be provided out of order. arg1 and arg2 are mandatory parameters and if not passed to the function as named arguments, then they must be assigned in order from the provided unnamed arguments. kw1 and kw2 have default values provided in the function definition so they are not mandatory, but if not provided for as named arguments they will take any available values from the remaining provided unnamed arguments. Any unnamed arguments left over are provided to the function in an array called args Any named arguments that do not have a corresponding parameter name in the function definition are provided to the function call in a dictionary called kwargs.

🌐
Manifoldapp
cuny.manifoldapp.org › read › how-to-code-in-python-3 › section › 46d41008-33ca-4f32-9937-7ddb9a86c5ce
How To Use *args and **kwargs | How To Code in Python 3 | Manifold @CUNY
It is important to keep the order of arguments in mind when creating functions so that you do not receive a syntax error in your Python code. We can also use *args and **kwargs to pass arguments into functions. First, let’s look at an example with *args. ... def some_args(arg_1, arg_2, arg_3): print("arg_1:", arg_1) print("arg_2:", arg_2) print("arg_3:", arg_3) args = ("Sammy", "Casey", "Alex") some_args(*args)
Top answer
1 of 13
971

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith

The Python Tutorial contains a good explanation of how it works, along with some nice examples.

Python 3 update

For Python 3, instead of iteritems(), use items()

2 of 13
386

Unpacking dictionaries

** unpacks dictionaries.

This

func(a=1, b=2, c=3)

is the same as

args = {'a': 1, 'b': 2, 'c':3}
func(**args)

It's useful if you have to construct parameters:

args = {'name': person.name}
if hasattr(person, "address"):
    args["address"] = person.address
func(**args)  # either expanded to func(name=person.name) or
              #                    func(name=person.name, address=person.address)

Packing parameters of a function

  • Use .items() instead of .iteritems() for python 3
def setstyle(**styles):
    for key, value in styles.iteritems():      # styles is a regular dictionary
        setattr(someobject, key, value)

This lets you use the function like this:

setstyle(color="red", bold=False)

Notes

  • kwargs is variable name used for keyword arguments, another variable name can be used. The important part is that it's a dictionary and it's unpacked with the double asterisk operator **.
  • Other iterables are unpacked with the single asterisk operator *
  • To prevent confusion, it's probably best to stick with the recognized variable names, kwargs and args, for dictionaries and other iterables respectively.

Resources

  • PEP 448: Additional Unpacking Generalizations
  • Real Python: Python args and kwargs: Demystified
  • What do * and ** before a variable name mean in a function signature?