Mastering *args and **kwargs in Python

Mastering *args and **kwargs in Python: In this article, we will learn about args and kwargs in Python. When writing functions in Python, flexibility is key – especially when you don’t always know how many arguments you will need to handle. That’s where args and kwargs come in.

These two special syntaxes allow you to write more dynamic and versatile functions by accepting a variable number of positional and keyword arguments. 

Whether you are building utility functions, decorators, or APIs, understanding argos and kwargs can make your code cleaner, more readable and more adaptable.  In this post, we will break down the differences between them, explore when and how to use each to master these essential Python features.

Difference between *args and **kwargs in Python

In Python, args and kwargs are special syntaxes used in function definitions to handle a variable number of arguments. 

*args (Arbitrary Positional Arguments / Non-keyword Arguments) 

The args syntax allows a function to accept an arbitrary number of non-keyworded(positional) arguments. When args is used in a function definition, all the non-keyworded arguments passed to the function are packed into a tuple. 

Meaning: args collect positional arguments into a tuple.

Use Case: When we are not sure how many positional arguments will be passed to the function.

Example

def my_function(*args):

    for arg in args:

       print(arg)

my_function(1,2,3,4,5)

#Output:

1

2

3

4

5

Internally, args is a tuple: (1, 2, 3, 4, 5)

**Kwargs (Keyword Arguments) 

Keyword arguments in Python are arguments that are passed to a function by explicitly specifying the parameter name, followed by a value using the = sign.

Meaning: **kwargs collect keyword arguments into a dictionary.

Use Case: When you are not sure how many named arguments will be passed.

Example:

def my_function(**kwargs):

    for key,value in kwargs.items():

       print(f"{key}={value}")

my_function(a=1,c=2,d=3,e=4,f=5)

#Output 

a=1

c=2

d=3

e=4

f=5

Internally , kwargs is a dict: {‘a’:1, ‘c’:2, ‘d’:3,’e’:4,’f’:5}

We can use both together.

def my_function(*args, **kwargs):

    print("Args:", args)

    print("Kwargs:", kwargs)

my_function(1,2,3,e=4,f=5)

#Output

Args: (1, 2, 3)

Kwargs: {‘e’: 4, ‘f’: 5}

Summary Table(*args vs **kwargs)

Feature*args**kwargs
TypeTupleDictionary
CapturesPositional argumentsKeyword (named) arguments
Syntax*args**kwargs
UsageVariable-length positional inputVariable-length keyword input

Conclusion:

In conclusion, *args and **kwargs are powerful features in Python that allow you to write more dynamic, reusable, and flexible functions. By understanding how positional and keyword arguments work—and when to use each—you can build functions that adapt to a wide range of input without sacrificing readability.

📌 Frequently Asked Questions (FAQ)

❓ What is the difference between *args and **kwargs in Python?

*args is used to pass a variable number of positional arguments to a function, while **kwargs is used to pass a variable number of keyword (named) arguments. args is a tuple, and kwargs is a dictionary inside the function.

❓ When should I use *args and **kwargs?

Use *args when you want to allow your function to accept an unknown number of positional arguments, and **kwargs when you want to accept an unknown number of keyword arguments. They are especially useful when writing decorators or wrapper functions.

❓ Can I use *args and **kwargs together in the same function?

Yes, you can use both in the same function. The correct order in the function definition is:

❓ Are *args and **kwargs required in a function?

No, they are optional. You only use them when you need to allow a flexible number of arguments. For most simple functions, standard parameters are sufficient.

❓ How do I access values inside *args and **kwargs?

*args behaves like a tuple: you can iterate over it or access by index.

**kwargs behaves like a dictionary: you can iterate over .items() or access values by keys.

Example:
def example(*args, **kwargs):
    print(args[0])          # First positional argument
    print(kwargs[“name”])   # Value of keyword argument ‘name’

❓ Can I pass a list or dictionary into *args and **kwargs?

Yes! You can unpack a list into *args and a dictionary into **kwargs when calling a function:
my_list = [1, 2, 3]
my_dict = {‘a’: 10, ‘b’: 20}
my_function(*my_list, **my_dict)

Keep practicing with real examples, and soon you will find them an indispensable part of your coding toolkit.

Happy Coding 🙂

Leave a Comment