Difference Between *args and **kwargs in Python

As a Python developer, when defining functions in Python, I encounter situations where I need to pass a variable number of arguments. Python provides two special syntax options to handle such cases: *args and **kwargs. In this tutorial, we will see the details difference between *args and **kwargs with examples and screenshots of executed example code.

*args in Python

The *args syntax allows you to pass a variable number of positional arguments to a function. When you prefix an argument with an asterisk (*), it collects all the positional arguments into a tuple within the function. Here’s an example:

def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

result = sum_numbers(1, 2, 3, 4, 5)
print(result)  

Output:

15

I have executed the above example code and added the screenshot below

args and kwargs in Python

In this example, the sum_numbers() function accepts any number of arguments using *args. Inside the function, args is treated as a tuple, allowing you to iterate over the passed arguments and perform operations like summing them up.

The *args syntax provides flexibility when you don’t know the exact number of arguments beforehand. It allows you to pass a varying number of arguments to the function without explicitly specifying them in the function definition.

Read Difference Between is and == in Python

**kwargs in Python

The **kwargs syntax allows you to pass a variable number of keyword arguments to a function. When you prefix an argument with two asterisks (**), it collects all the keyword arguments into a dictionary within the function. Here’s an example:

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="New York")

Output:

name: Alice
age: 25       
city: New York

I have executed the above example code and added the screenshot below

Between args and kwargs in Python

In this example, the print_info() function accepts any number of keyword arguments using **kwargs. Inside the function, kwargs is treated as a dictionary, allowing you to access the passed keyword arguments using their respective keys.

The **kwargs syntax is particularly useful when you want to pass optional or named arguments to a function. It provides a clean and readable way to handle keyword arguments without explicitly specifying them in the function definition.

Combine *args and **kwargs in Python

You can combine both *args and **kwargs in a function definition to accept both positional and keyword arguments. Here’s an example:

def my_function(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

my_function(1, 2, 3, name="Alice", age=25)
# Output:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 25}

In this case, the my_function() accepts both positional arguments (*args) and keyword arguments (**kwargs). Inside the function, args is a tuple containing the positional arguments, and kwargs is a dictionary containing the keyword arguments.

Check out How to Use wait() Function in Python?

Use *args and **kwargs for Function Calls in Python

In addition to using *args and **kwargs in function definitions, you can also use them when calling functions. This allows you to pass a tuple or list as individual positional arguments and a dictionary as individual keyword arguments. Here’s an example:

def greet(name, age):
    print(f"Hello, {name}! You are {age} years old.")

args = ("Alice", 25)
kwargs = {"age": 30}

greet(*args)  # Output: Hello, Alice! You are 25 years old.
greet("Bob", **kwargs)  # Output: Hello, Bob! You are 30 years old.

In this example, *args is used to unpack the tuple args into individual positional arguments, and **kwargs is used to unpack the dictionary kwargs into individual keyword arguments when calling the greet() function.

Read Is Python a Good Language to Learn?

Summary

SyntaxDescription
*argsAllows passing a variable number of positional arguments as a tuple
**kwargsAllows passing a variable number of keyword arguments as a dictionary
  • *args collects positional arguments into a tuple within the function.
  • **kwargs collects keyword arguments into a dictionary within the function.
  • Both *args and **kwargs can be combined in a function definition.
  • *args and **kwargs can also be used when calling functions to unpack tuples/lists and dictionaries, respectively.

Check out What Is the Best Way to Learn Python?

Conclusion

In this tutorial, I helped you to understand the difference between *args and **kwargs. I discussed *args in Python and **kwargs in Python. We saw how to combine *args and **kwargs in Python, and use *args and **kwargs for functional calls in Python and summary.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.