args (arguments) and kwargs (keyword arguments) in Python

In Python, “args” and “kwargs” are used to handle variable-length arguments in functions. They allow you to pass a variable number of arguments to a function. This flexibility is useful when you’re not sure how many arguments will be passed to the function, or when you want to pass a varying number of arguments.

Understanding “args” (arguments)
“args” is a tuple that allows you to pass a variable number of positional arguments to a function. When you define a function with *args, it means that the function can accept any number of arguments. These arguments are captured as a tuple inside the function.

let us understand it taking an example in real time

Imagine you’re building a function that calculates the total price of items in a shopping cart. Instead of limiting the number of items the function can calculate, you can use *args to allow for a variable number of items.

def calculate_total(*args):
    total = 0
    for price in args:
        total += price
    return total

# Calculate total price for items in shopping cart
total_price = calculate_total(10.99, 5.99, 7.50, 3.25)
print(f"Total price: ${total_price}")

Output:

In this example, the calculate_total function can accept any number of item prices as arguments. These prices are passed as a tuple args, allowing the function to calculate the total price regardless of the number of items in the cart.

Lets us take another example

def my_function(*args):
    for arg in args:
        print(arg)

my_function('Hello', 'World', 'Python')  # Output: Hello World Python

In this example, the function my_function accepts any number of arguments and prints each argument.

Understanding “kwargs” (keyword arguments)
“kwargs” is a dictionary that allows you to pass a variable number of keyword arguments to a function. When you define a function with **kwargs, it means that the function can accept any number of keyword arguments. These arguments are captured as a dictionary inside the function.

Imagine you’re hosting a party and you want to keep track of what food and drinks your guests prefer. You can use **kwargs to collect this information, as it allows you to pass a variable number of preferences as keyword arguments.

def guest_preferences(**kwargs):
    for guest, preference in kwargs.items():
        print(f"{guest} prefers {preference}")

# Collect guest preferences
guest_preferences(Alice="pizza", Bob="sushi", Carol="burgers")

Output:

In this example, the guest_preferences function accepts any number of guest names and their food preferences as keyword arguments (**kwargs). The arguments are passed as a dictionary, allowing the function to print each guest’s name along with their preferred food.

Using “args” and “kwargs” together
You can use “args” and “kwargs” together in a function definition to accept both positional and keyword arguments.

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

my_function('Hello', 'World', name='Alice', age=30)  
# Output: Hello World, name: Alice, age: 30

In this example, the function my_function accepts both positional arguments and keyword arguments, and prints them accordingly.

Conclusion

“args” and “kwargs” provide a powerful way to handle variable-length arguments in Python functions. They allow you to create flexible and versatile functions that can accept a varying number of arguments, making your code more dynamic and easier to maintain.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>