What Is The Difference Between *args and **kwargs In Python

When you define or invoke a python function, you may find the function argument is something like *args or **kwargs. This kind of argument is very strange to python beginners. Of cause it is not pointer or pointer array like in C or C++ programming language. It is just a flexiable way which can let you define or pass multiple number of function arguments. Let me show you an example as below.

1. Define Python Function With *args Argument.

If a function define argument as *args, this means you can pass any number of argument to this function, and all the argument will be accessed by args as a tuple. Below is the example.

  1. Define a python function that has *args argument.
    >>> def test_arg(*args):
    ...     for arg in args:
    ...         print(arg)
    
  2. Invoke above function with multiple arguments.
    >>> test_arg(1,2,3,4,5,'python')
    1
    2
    3
    4
    5
    python
    
  3. Invoke above function with different parameters.
    >>> test_arg('python', '*args')
    python
    *args
    

2. Define Python Function With **kwargs Argument.

The **kwargs argument is a dictionary argument, kwargs is the abbreviation of key word arguments. It means all the function keyword value pair arguments can be accessed use kwargs as a dictionary.

  1. Define a python function take **kwargs arguments.
    >>> def test_kwargs(**kwargs):
            # loop in the kwargs dictionary object.     
    ...     for key in kwargs:
                # extract the key related value.
    ...         value = kwargs[key]
                # print out key and value.
    ...         print(key, value)
    
  2. Invoke above function with provided key value pair arguments.
    >>> test_kwargs(user_name='jerry', password='888888', salary=10000)
    user_name jerry
    password 888888
    salary 10000
    

3. Define Python Function With Both *args And **kwargs Argument.

When you define a python function, you can mixed use *args and **kwargs as the function arguments like below.

>>> def test_args_kwargs(user_name, *args, **kwargs):
        # the first argument is a normal argument.
...     print('user_name = ', user_name)
   
        # print out the key word argument key and value.
...     for key in kwargs:
...         value = kwargs[key]
...         print(key, value)

        # print out the multiple number arguments tuple.
...     for arg in args:
...         print(arg)
... 
# invoke above function
>>> test_args_kwargs('jerry', '999999',80000, age=25, sex='male')
user_name =  jerry
age 25
sex male
999999
80000

4. Use * To Pass List Argument To Python Function.

If you want to pass a python list object to function which has *args argument, you should pass the list argument with * at the argument beginning, it will tell the function, this argument is a list.

# first define a python list variable.
>>> args = [1,2,3,4,5,'python']
# invoke test_arg function and pass above list values. use *args to extract the list values.
>>> test_arg(*args)
1
2
3
4
5
python

5. Use * To Extract Part Of A Python List.

>>> x,*y,z = [1,2,3,4,5,6]
>>> print(x)
1
>>> print(y)
[2, 3, 4, 5]
>>> print(z)
6

6. Use ** To Pass Dictionary Argument To Python Function.

When you want to pass a dicionary argument to a python function, you need to add ** at the beginning of the dictionary argument.

>>> kwargs = {'user_name':'jerry','password':'999999','salary':10000}
>>> 
>>> test_kwargs(**kwargs)
user_name jerry
password 999999
salary 10000

If you do not add ** at the beginning of argument, it will throw an error.

>>> test_kwargs(kwargs)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test_kwargs() takes 0 positional arguments but 1 was given

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.