DEV Community

Samita Khanduri
Samita Khanduri

Posted on

1

Understanding *args and **kwargs in Python

Understanding *args and **kwargs in Python with Beginner-Friendly Examples

In Python, *args and **kwargs are powerful features that let you create flexible functions that can accept a variable number of arguments. These are especially useful when you don't know in advance how many arguments will be passed to your function.


What is *args?

*args allows a function to accept any number of positional arguments. These arguments are stored in a tuple.

Example:

def print_numbers(*args):
    for number in args:
        print(number)

print_numbers(1, 2, 3, 4, 5)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Here, you can pass as many numbers as you want, and they will all be printed. If no arguments are passed, args will simply be an empty tuple.


What is **kwargs?

**kwargs allows a function to accept any number of keyword arguments. These arguments are stored in a dictionary, where the keys are the argument names and the values are their corresponding values.

Example:

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

print_info(name="Alice", age=25, city="New York")
Enter fullscreen mode Exit fullscreen mode

Output:

name: Alice
age: 25
city: New York
Enter fullscreen mode Exit fullscreen mode

Here, you can pass as many key-value pairs as you want. If no keyword arguments are passed, kwargs will simply be an empty dictionary.


Combining *args and **kwargs

You can use both *args and **kwargs in the same function. This allows you to handle both positional and keyword arguments.

Example:

def describe_person(*args, **kwargs):
    print("Attributes:")
    for arg in args:
        print(f"- {arg}")

    print("\nDetails:")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

describe_person("Friendly", "Helpful", name="Bob", age=30, city="Boston")
Enter fullscreen mode Exit fullscreen mode

Output:

Attributes:
- Friendly
- Helpful

Details:
name: Bob
age: 30
city: Boston
Enter fullscreen mode Exit fullscreen mode

Here, *args collects positional arguments (like "Friendly" and "Helpful"), and **kwargs collects keyword arguments (like name="Bob" and age=30).


Simple Rules to Remember

  1. Use *args when you need to pass a variable number of positional arguments.
  2. Use **kwargs when you need to pass a variable number of keyword arguments.
  3. The order in the function signature should always be:
    • Regular positional arguments
    • *args
    • Default keyword arguments
    • **kwargs

Practical Examples for Beginners

Example 1: A Function to Add Numbers

def add_numbers(*args):
    total = sum(args)
    print(f"The sum is: {total}")

add_numbers(1, 2, 3, 4)
add_numbers(10, 20)
Enter fullscreen mode Exit fullscreen mode

Output:

The sum is: 10
The sum is: 30
Enter fullscreen mode Exit fullscreen mode

Example 2: Greeting People by Name

def greet_people(**kwargs):
    for name, greeting in kwargs.items():
        print(f"{greeting}, {name}!")

greet_people(Alice="Hello", Bob="Hi", Charlie="Hey")
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Alice!
Hi, Bob!
Hey, Charlie!
Enter fullscreen mode Exit fullscreen mode

Example 3: Combining *args and **kwargs in a Shopping List

def shopping_list(*items, **prices):
    print("Items to buy:")
    for item in items:
        print(f"- {item}")

    print("\nPrices:")
    for item, price in prices.items():
        print(f"{item}: ${price}")

shopping_list("Apples", "Bananas", Apples=2, Bananas=1.5, Oranges=3)
Enter fullscreen mode Exit fullscreen mode

Output:

Items to buy:
- Apples
- Bananas

Prices:
Apples: $2
Bananas: $1.5
Oranges: $3
Enter fullscreen mode Exit fullscreen mode

Conclusion

By using *args and **kwargs, you can make your Python functions more dynamic and flexible. This is especially useful when working on programs where the number of inputs might vary. Start experimenting with these features in small projects, and you'll see how handy they can be!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay