Welcome! Today, we’re going to learn something fun and useful in Python—how to use *args and **kwargs. I’ll explain it in the simplest way possible, with lots of examples, so don’t worry if you’re just getting started with Python. By the end, you’ll understand how to use these like a pro!

👉 Before diving deep into the article, make sure that you know about Python functions.

Now let’s start learning…

What Are *args and **kwargs?

Imagine you’re writing a function, but you don’t know how many inputs it will get. Sometimes you need to handle a few inputs, and sometimes a lot! That’s where *args and **kwargs come in. They’re like magic bags that can hold different amounts of inputs!

  • *args: Think of this as a bag that can hold a bunch of unnamed items. These items get stored in a special type of container called a tuple.
  • **kwargs: This is a bag for named items—think of it like a list where each item has a label, like name="John". These items get stored in a dictionary.

Example for *args:

def show_items(*args):
    print("Items in args:", args)

show_items(1, 2, 3, "apple", "banana")

Output:

Items in args: (1, 2, 3, 'apple', 'banana')

Here, all the extra arguments (1, 2, 3, "apple", "banana") are bundled into a tuple and printed.

Example for **kwargs:

def show_keywords(**kwargs):
    print("Items in kwargs:", kwargs)

show_keywords(name="John", age=25, city="New York")

Output:

Items in kwargs: {'name': 'John', 'age': 25, 'city': 'New York'}

Why Should I Use *args and **kwargs?

Sometimes, you don’t know how many inputs you’ll get, and you want to make your function flexible enough to handle any number of inputs.

Example:

Let’s say you’re building a greet_people function, but you don’t know how many people you need to greet. Here’s how *args can help:

def greet_people(*args):
    for person in args:
        print(f"Hello, {person}!")
        
greet_people("John", "Jane", "Doe")

Output:

Hello, John!
Hello, Jane!
Hello, Doe!

In this example, you don’t have to know how many names will be passed into the function. *args collects all the names into a tuple and handles it.

For **kwargs, you can use it to collect named information.

Example:

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

display_info(name="John", age=25, city="New York")

Output:

name: John
age: 25
city: New York

Here, **kwargs gathers all the name-value pairs into a dictionary and prints each key-value pair.

Do I Have to Use the Names args and kwargs?

No, the names args and kwargs are just conventions—they’re commonly used to make your code easy to understand for others. But you could use other names if you wanted, though it’s best to stick with args and kwargs for consistency.

def my_func(*numbers, **info):
    print("Numbers:", numbers)
    print("Info:", info)

my_func(1, 2, 3, name="Alice", age=30)

Output:

Numbers: (1, 2, 3)
Info: {'name': 'Alice', 'age': 30}

Here, numbers is like *args and info is like **kwargs, but you can see that changing the names doesn’t affect how they work.

Using *args and **kwargs With Normal Parameters

You can also mix normal parameters (the usual ones you write in functions) with *args and **kwargs. The normal parameters are just regular inputs that have to be passed first.

def introduce(normal_param, *args, **kwargs):
    print(f"Normal Parameter: {normal_param}")
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")
    
introduce("I’m normal!", "John", "Jane", name="Doe", age=25)

Output:

Normal Parameter: I’m normal!
Args: ('John', 'Jane')
Kwargs: {'name': 'Doe', 'age': 25}

Putting It All Together: Using Normal Parameters, Default Parameters, *args, and **kwargs

Now, let’s combine everything into one function: normal parameters, default parameters, *args, and **kwargs.

Here’s how to remember the correct order for these types of arguments—NADK:

  1. N – Normal parameters
  2. A*args (extra arguments)
  3. D – Default parameters
  4. K**kwargs (keyword arguments)

NOTE: These orders are important, and if you do not follow them, it will give an error.

Example Using NADK Order:

def full_example(normal, *args, default=10, **kwargs):
    print("Normal:", normal)
    print("Args:", args)
    print("Default:", default)
    print("Kwargs:", kwargs)

full_example("Required", 1, 2, 3, default=20, name="Alice", age=30)

Output:

Normal: Required
Args: (1, 2, 3)
Default: 20
Kwargs: {'name': 'Alice', 'age': 30}

  • Normal parameter: "Required"
  • *args: collects extra numbers (1, 2, 3) into a tuple.
  • Default parameter: starts with 10, but we can change it to 20.
  • **kwargs: collects the keyword arguments into a dictionary ({'name': 'Alice', 'age': 30}).

Conclusion

That’s it! Now you know how to use *args and **kwargs in your Python functions. Let’s do a quick recap:

  • *args collects multiple arguments into a tuple.
  • **kwargs collects multiple keyword arguments into a dictionary.
  • You can combine normal parameters, default parameters, *args, and **kwargs in the same function.
  • The order to remember is NADK—Normal, Args, Default, Kwargs.

These concepts make your functions more flexible and powerful. Keep practicing, and soon you’ll be using *args and **kwargs like a pro. Happy coding! 😊

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment