Open In App

*args and **kwargs in Python

Last Updated : 19 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will cover what ** (double star/asterisk) and * (star/asterisk) do for parameters in Python,  Here, we will also cover args and kwargs examples in Python. We can pass a variable number of arguments to a function using special symbols. 

There are two special symbols:

*args and **kwargs in Python

*args and **kwargs in Python

Special Symbols Used for passing arguments in Python:

  • *args (Non-Keyword Arguments)
  • **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.” 

What is Python *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-keyworded, 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 is able to multiply them all together. It can be done using *args.
  • Using the *, the variable that we associate with the * becomes iterable meaning you can do things like iterate over it, run some higher-order functions such as map and filter, etc.

Example 1:

Python program to illustrate *args for a variable number of arguments

python
def myFun(*argv):
    for arg in argv:
        print(arg)


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

Output:

Hello
Welcome
to
GeeksforGeeks

Example 2:

Python program to illustrate *args with a first extra argument

Python
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

What is Python **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 that 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 1: 

Python program to illustrate *kwargs for a variable number of keyword arguments. Here **kwargs accept keyworded variable-length argument passed by the function call. for first=’Geeks’ first is key and ‘Geeks’ is a value. in simple words, what we assign is value, and to whom we assign is key. 

Python
def myFun(**kwargs):
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))


# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

Output:

first == Geeks
mid == for
last == Geeks
 

Example 2:

Python program to illustrate  **kwargs for a variable number of keyword arguments with one extra argument. All the same, but one change is we passing non-keyword argument which acceptable by positional argument(arg1 in myFun). and keyword arguments we passing are acceptable by **kwargs. simple right?

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

first == Geeks
mid == for
last == Geeks

Using both *args and **kwargs in Python to call a function

Example 1:

Here, we are passing *args and **kwargs as an argument in the myFun function. Passing *args to myFun simply means that we pass the positional and variable-length arguments which are contained by args. so, “Geeks” pass to the arg1 , “for” pass to the arg2, and “Geeks” pass to the arg3. When we pass **kwargs as an argument to the myFun it means that it accepts keyword arguments. Here, “arg1” is key and the value is “Geeks” which is passed to arg1, and just like that “for” and “Geeks” pass to arg2 and arg3 respectively. After passing all the data we are printing all the data in lines. 

python
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

Example 2:

Here, we are passing *args and **kwargs as an argument in the myFun function. where ‘geeks’, ‘for’, ‘geeks’ is passed as *args, and first=”Geeks”, mid=”for”, last=”Geeks”  is passed as **kwargs and printing in the same line.

python
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'}

Using *args and **kwargs in Python to set values of object

  • *args receives arguments as a tuple.
  • **kwargs receives arguments as a dictionary.

Example 1: using Python *args

Python
# defining car class
class Car():
    # args receives unlimited no. of arguments as an array
    def __init__(self, *args):
        # access args index like array does
        self.speed = args[0]
        self.color = args[1]


# creating objects of car class
audi = Car(200, 'red')
bmw = Car(250, 'black')
mb = Car(190, 'white')

# printing the color and speed of the cars
print(audi.color)
print(bmw.speed)

Output:

red
250

Example 2: using Python **kwargs

Python
# defining car class
class Car():
    # args receives unlimited no. of arguments as an array
    def __init__(self, **kwargs):
        # access args index like array does
        self.speed = kwargs['s']
        self.color = kwargs['c']


# creating objects of car class
audi = Car(s=200, c='red')
bmw = Car(s=250, c='black')
mb = Car(s=190, c='white')

# printing the color and speed of cars
print(audi.color)
print(bmw.speed)

Output:

red
250

*args and **kwargs in Python – FAQs

Why use *args and **kwargs in Python?

*args and **kwargs allow functions to accept a variable number of arguments:

  • *args (arguments) allows you to pass a variable number of positional arguments to a function.
  • **kwargs (keyword arguments) allows you to pass a variable number of keyword arguments (key-value pairs) to a function.

Difference between *args and **kwargs in Python?

*args collects additional positional arguments as a tuple, while **kwargs collects additional keyword arguments as a dictionary.

def example_function(*args, **kwargs):
print(args) # tuple of positional arguments
print(kwargs) # dictionary of keyword arguments

example_function(1, 2, 3, name='Alice', age=30)
Output:
(1, 2, 3)
{'name': 'Alice', 'age': 30}

Is *args a list or tuple in Python?

*args collects additional positional arguments into a tuple, not a list. The arguments are accessible using tuple indexing and iteration.

def example_function(*args):
print(type(args)) # <class 'tuple'>
example_function(1, 2, 3)

Why use *args instead of a list?

*args is used when you want to pass a variable number of arguments to a function without explicitly specifying each argument in a list. It allows for flexibility and simplicity when defining functions that may take an unknown number of arguments.

def sum_values(*args):
total = sum(args)
return total
result = sum_values(1, 2, 3, 4, 5)
print(result) # Output: 15

How to pass **kwargs?

To pass keyword arguments (**kwargs) to a function, you provide key-value pairs when calling the function.

def example_function(**kwargs):
print(kwargs)
example_function(name='Alice', age=30)
Output:
{'name': 'Alice', 'age': 30}

Inside the function, kwargs will be a dictionary containing the passed keyword arguments.




Previous Article
Next Article

Similar Reads

What Does Super().__Init__(*Args, **Kwargs) Do in Python?
In Python, super().__init__(*args, **kwargs) is like asking the parent class to set itself up before adding specific details in the child class. It ensures that when creating an object of the child class, both the parent and child class attributes are initialized correctly. It's a way of saying, In this article, we will see about super().__init__()
4 min read
Transfer Kwargs Parameter to a Different Function in Python
In Python, **kwargs is a special syntax that allows a function to accept any number of keyword arguments. When transferring **kwargs parameters to a different function, involves passing the received keyword arguments to another function using the same **kwargs syntax. In this article, we will explore different approaches to pass kwargs as a Paramet
3 min read
Using Request Args for a Variable URL in Flask
This article will teach us how to use Request Arguments in our Flask application. First, we will understand. What are the Request Arguments? What are the Request Arguments? Request Arguments are MultiDict objects with the parsed contents of the query string (the part in the URL after the question mark). MultiDict: It is a dictionary-like structure,
5 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg