Python Using *Args And **Kwargs Tutorial – Complete Guide

Welcome to this enlightening tutorial on using *args and **kwargs in Python. These keywords are mystical to many beginners, but by the end of this guide, you’ll see they are not as complex as they appear.

What is *args and **kwargs?

In Python, *args and **kwargs are special syntaxes used in function definition. They allow a function to accept optional arguments, making your code more flexible and cleaner.

Mastering *args and **kwargs can take your Python coding skills to the next level. They are not only important for writing versatile functions but are also widely used in many Python packages and frameworks.

Undeniably, understanding and effectively implementing these concepts can make you stand out as a Pythonista, making your road in Python programming world smoother. So, let’s get started!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Decoding *args

The keyword *args stands for ‘arguments’. In Python function, it enables us to pass varying number of positional arguments. Here is a rudimentary example:

def add_numbers(*args):
    return sum(args)
print(add_numbers(1, 2, 3, 4, 5))  # Output: 15

In the code above, we define a function called add_numbers that takes any number of arguments, adds them up and returns the sum. The special syntax *args collects all the positional arguments into a tuple, allowing this kind of flexibility.

Understanding **kwargs

On the other hand, **kwargs stands for ‘keyword arguments’. It enables us to pass varying number of keyword or named arguments. Here is a simple example:

def print_data(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_data(Name='John', Age=25, Country='USA')

In this case, the function print_data takes any number of keyword arguments and prints each key-value pair. The **kwargs collects all the keyword arguments into a dictionary.

Using *args and **kwargs Together

We can use *args and **kwargs together in a function to accept any number of positional and keyword arguments. The positional arguments should be placed before keyword arguments. Let’s look at an example:

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

func(1, 2, 3, Name='John', Age=25)

Advanced Examples and Usage of *args

Now, let’s take a deeper dive into the practical application of *args in Python with some examples.

Example 1: Calculating the Product of Inputs

def multiply(*args):  
    product = 1
    for num in args:  
        product *= num
    return product

print(multiply(1, 2, 3, 4))  # Output: 24

In this example, we define a function ‘multiply’ that takes any number of arguments and multiplies them.

Example 2: Handling Unpredictable Number of Arguments

def print_random_things(*args):
    for thing in args:
        print(thing)

print_random_things('apple', 'banana', 'cherry', 'dates', 'elderberry')

This function ‘print_random_things’ simply prints everything that has been passed as arguments.

Example 3: Using *args with Normal Parameters

def func(arg1, arg2, *args):
    print("First argument :", arg1)
    print("Second argument :", arg2)
    print("The other arguments are :", args)

func('Apple', 'Banana', 'Cherry', 'Dates', 'Elderberry')

Here, we exemplify the use of *args with normal parameters where ‘arg1’ and ‘arg2’ are normal arguments and we use *args for the rest.

Example 4: Combining *args in Function Calls

def func(*args):
    for i in args:
        print(i)

fruits = ('Apple', 'Banana', 'Cherry')
func(*fruits)

In this last example, we pass a tuple to a function as an argument using *args.

Advanced Examples and Usage of **kwargs

Let’s dive deeper into the practical usage of **kwargs with some more advanced examples.

Example 1: Creating a Simple Data Display Function with **kwargs

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

display_data(Name='John', Age=25, Country='USA')

Here, key-value pairs are displayed as a way of showcasing data.

Example 2: Using **kwargs with Regular Parameters

def func(arg1, arg2, **kwargs):
    print("First argument :", arg1)
    print("Second argument :", arg2)
    for key in kwargs:
        print(f"{key}: {kwargs[key]}")

func("Apple", "Banana", Color="Red", Taste="Sweet")

This second example demonstrates how to use **kwargs with other regular arguments.

Example 3: Using **kwargs to Construct Dictionaries

def construct_dictionary(**kwargs):
    return kwargs

print(construct_dictionary(name='John', age=25, country='USA'))

**kwargs can be used to build dictionaries, as shown in the example above.

Example 4: Passing Dictionaries with **kwargs in Function Calls

def func(**kwargs):
    for key in kwargs:
        print(f"{key}: {kwargs[key]}")

data = {'Name': 'John', 'Age': 25}
func(**data)

Finally, we can use **kwargs to pass a dictionary to a function as keyword arguments.-

By mastering these applications of *args and **kwargs, you’ll be able to write extremely versatile Python functions and work with third-party libraries much more effectively!

More Practical Examples Combining *args and **kwargs

Now that we have a good understanding of both *args and **kwargs individually, let’s review some examples where these two features are used together in Python functions.

Example 1: Using *args and **kwargs in the Same Function

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

func(1, 2, 3, First_Name='John', Last_Name='Doe', Age=25)

Here, we create a function uses both *args and **kwargs to handle variable numbers of positional and keyword arguments.

Example 2: Using Default Parameters, *args, and **kwargs in the Same Function

def func(arg1, arg2, *args, kwarg1='Default', **kwargs):
    print("First Positional Argument:", arg1)
    print("Second Positional Argument:", arg2)
    print("---Variable Arguments---")
    for arg in args:
        print(arg)
    print("\nKeyword Argument 1:", kwarg1)
    print("----Variable Keyword Arguments---")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

func('Fish', 'Chicken', 'Pasta', 'Rice', kwarg1='Not default', Cuisine='Italian', Dish='Pizza')

In this example, we highlight how we can combine default parameters, *args and **kwargs together in one function.

Example 3: *args for Unpacking, **kwargs for Named Attributes

def func(*args, **kwargs):
    print(args)
    print(kwargs)

values = (1, 2, 3, 4, 5)
attributes = {'Name': 'John', 'Age': 25, 'Country': 'USA'}

func(*values, **attributes)

This example shows how you can use *args and **kwargs to unpack arguments and keyword arguments from tuples and dictionaries when calling a function.

Example 4: Passing *args and **kwargs to Another Function

def func1(*args, **kwargs):
    print("Inside func1:")
    print(args)
    print(kwargs)
    print("Calling func2 from func1 with arguments:")
    func2(*args, **kwargs)

def func2(*args, **kwargs):
    print("Inside func2:")
    print(args)
    print(kwargs)

values = (1, 2, 3, 4, 5)
attributes = {'Name': 'John', 'Age': 25, 'Country': 'USA'}

func1(*values, **attributes)

This last example exhibits a common pattern in Python where *args and **kwargs are collected in one function just to be passed onto another function.

All these examples demonstrate that *args and **kwargs are more than just mysterious syntax in Python function definitions. By leveraging these two keywords, you can make your Python functions incredibly dynamic and adaptable to a wide range of use cases.

Where to Go Next: Continue Your Python Journey With Zenva

Now that you’ve unravelled the mysteries of *args and **kwargs in Python, we encourage you to keep unlocking the rich potentials of Python programming.

As you continue on your learning journey, we invite you to explore our Python Mini-Degree.

This comprehensive program, not only covers the basics of Python programming, but also delves into complex concepts like algorithms, object-oriented programming, and even includes exciting hands-on projects in game development and app creation.

Our well-structured courses are authored by experienced programmers who hold certifications from industry leaders like Unity Technologies and CompTIA. By following along with the lessons, coding challenges, and quizzes, you get to reinforce your learning and build a rich portfolio of Python projects.

For a broader selection of our offerings, check out our Python Courses. Keep moving forward in your learning journey and become the Python expert you aspire to be with Zenva!

Conclusion

Taking the first steps towards mastering Python is an exciting journey, and understanding the usage of *args and **kwargs can lead your way to become a more confident and efficient Python programmer. These special syntaxes not only enrich your coding repertoire but are also your entry point into grasping more advanced Python concepts and frameworks.

With this tutorial, you’ve taken another step forward on your journey to mastering Python. Remember, understanding and implementing these versatile features paves the way to write cleaner and more efficient code. Continue growing your Python expertise and check out our comprehensive Python Mini-Degree. Trust us at Zenva with your learning journey, and soon, you’ll be coding like a pro! Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.