*args and **kwargs in Python

Published:9 min read

Difference Between *args and **kwargs

When you write functions in Python, sometimes you don’t know beforehand how many arguments (inputs) the function will receive. *args and **kwargs help you handle such situations.

  • *args lets a function accept any number of positional arguments (arguments without a name).
  • **kwargs lets a function accept any number of keyword arguments (arguments with a name).

Using *args and **kwargs makes your functions more flexible and reusable.

args and kwargs in Python

What is Python *args?

*args allows a function to take more positional arguments than you initially specified. The name *args is just a convention; you can name it anything, but *args is widely used and recommended for readability.

Syntax of Python *args

Here’s how you use *args in a function:

python
3 lines
|
16/ 500 tokens
1
2
3
def my_function(*args):
    for arg in args:
        print(arg)
Code Tools
  • def my_function(*args): This defines a function named my_function that takes any number of positional arguments.
  • args: Inside the function, args is treated as a tuple (a collection of items) containing all the extra arguments passed to the function.

Example

Let’s see *args in action with an example:

python
5 lines
|
27/ 500 tokens
1
2
3
4
5
def greet(*args):
    for name in args:
        print(f"Hello, {name}!")

greet("Alice", "Bob", "Charlie")
Code Tools

Output:

bash
3 lines
|
11/ 500 tokens
1
2
3
Hello, Alice!
Hello, Bob!
Hello, Charlie!
Code Tools

Explanation:

  • The greet function can accept any number of names.
  • Each name passed to the function is printed with a greeting.
  • You can pass as many names as you want without changing the function.

What is Python **kwargs?

While *args handles extra positional arguments, **kwargs handles extra keyword arguments. **kwargs allows you to pass a variable number of named arguments to a function.

Syntax of Python **kwargs

Here’s how you use **kwargs in a function:

python
3 lines
|
25/ 500 tokens
1
2
3
def my_function(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
Code Tools
  • def my_function(**kwargs): This defines a function named my_function that takes any number of keyword arguments.
  • kwargs: Inside the function, kwargs is treated as a dictionary (a collection of key-value pairs) containing all the extra keyword arguments passed to the function.

Example

Let’s see **kwargs in action with an example:

python
5 lines
|
38/ 500 tokens
1
2
3
4
5
def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=30, city="New York")
Code Tools

Output:

text
3 lines
|
9/ 500 tokens
1
2
3
name: Alice
age: 30
city: New York

Explanation:

  • The display_info function can accept any number of named arguments.
  • Each key-value pair passed to the function is printed.

*args and **kwargs in Python to Call a Function

You can use both *args and **kwargs in a single function to handle both positional and keyword arguments at the same time. This makes your function even more flexible.

Example

Here’s an example of a function that uses both *args and **kwargs:

python
5 lines
|
42/ 500 tokens
1
2
3
4
5
def combined_example(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

combined_example(1, 2, 3, name="Alice", age=30)
Code Tools

Output:

bash
2 lines
|
20/ 500 tokens
1
2
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 30}
Code Tools

Explanation:

  • The combined_example function accepts both extra positional and keyword arguments.
  • It prints out the positional arguments as a tuple and the keyword arguments as a dictionary.

Best Practices

Using *args and **kwargs can make your code powerful, but it’s important to use them wisely. Here are some best practices to follow:

1. Use Clear and Descriptive Names

While *args and **kwargs are common names, you can use more descriptive names if it makes your code easier to understand.

python
5 lines
|
41/ 500 tokens
1
2
3
4
5
def process_items(*items, **item_details):
    for item in items:
        print(item)
    for key, value in item_details.items():
        print(f"{key}: {value}")
Code Tools

2. Document Your Functions

Always explain what your function does and how it uses *args and **kwargs. This helps others (and yourself) understand your code later.

python
9 lines
|
66/ 500 tokens
1
2
3
4
5
6
7
8
9
def create_user(username, *args, **kwargs):
    """
    Creates a new user.

    :param username: The username of the new user.
    :param args: Additional positional arguments.
    :param kwargs: Additional keyword arguments like email, age, etc.
    """
    pass
Code Tools

3. Validate the Arguments

Even though *args and **kwargs are flexible, sometimes you need to check if the arguments passed meet certain criteria.

python
5 lines
|
56/ 500 tokens
1
2
3
4
5
def calculate_total(*args, discount=0):
    if not all(isinstance(arg, (int, float)) for arg in args):
        raise ValueError("All positional arguments must be numbers.")
    total = sum(args) - discount
    return total
Code Tools

4. Don’t Overuse *args and **kwargs

While they are useful, using too many *args and **kwargs can make your code hard to read. Use them only when necessary.

5. Order Matters in Function Definitions

When defining a function, place *args before **kwargs. Also, if you have regular parameters, they should come before *args and **kwargs.

python
2 lines
|
15/ 500 tokens
1
2
def example_function(a, b=2, *args, c=3, **kwargs):
    pass
Code Tools

6. Use Type Hinting

Adding type hints can make your code clearer and help tools understand your code better.

python
4 lines
|
22/ 500 tokens
1
2
3
4
from typing import Any

def display_info(*args: Any, **kwargs: Any) -> None:
    pass
Code Tools

Conclusion

*args and **kwargs is used for writing flexible and efficient Python functions. These functions allow you to accept numbers of arguments, making your code more adaptable to different situations.

By following the best practices, you can use *args and **kwargs effectively without making your code confusing. Practice using them in your projects to become more comfortable and to make your Python programming more powerful.

Frequently Asked Questions

The *args parameter allows a Python function to accept any number of positional arguments. This makes your functions more flexible by enabling them to handle varying amounts of input without needing to define each parameter explicitly.

In Python, *args and **kwargs are optional parameters that let functions accept variable numbers of arguments. *args handles extra positional arguments, while **kwargs manages additional keyword arguments, enhancing the flexibility and reusability of your functions.

In Python function arguments, the * symbol before a parameter name (like *args) indicates that the function can accept an arbitrary number of positional arguments. It collects these arguments into a tuple, allowing the function to process inputs dynamically.

The main difference between *args and **kwargs is the type of arguments they handle. *args is used for positional arguments and collects them into a tuple, whereas **kwargs is used for keyword arguments and stores them in a dictionary. This distinction allows functions to manage different kinds of inputs efficiently.

In Python, *args allows passing a variable number of positional arguments to a function, while **kwargs allows passing a variable number of keyword arguments.

*args is a special syntax used in function definitions to accept multiple positional arguments, whereas args is just a regular variable name.

In a function definition, *args comes before **kwargs because positional arguments must be specified before keyword arguments. For example: def func(*args, **kwargs):.

Still have questions?Contact our support team

Related Articles

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.