Difference between *args and **kwargs

 Follow me


*args: Positional Arguments

Think of *args as a way to handle multiple positional arguments (those without a name, just like usual function arguments). Normally, functions have a fixed number of arguments, but with *args, you can pass as many as you want!

How *args Works

  • When you write *args in a function, it gathers all extra positional arguments into a tuple.
  • You can call this args anything you want (e.g., *numbers), but by convention, we use *args.

Example:

Python

def greet(*args): for name in args: print(f"Hello, {name}!") # Call the function with multiple names greet("Alice", "Bob", "Charlie")

Output:

Hello, Alice! Hello, Bob! Hello, Charlie!

Explanation:

  • *args takes "Alice", "Bob", and "Charlie" and puts them in a tuple called args.
  • The function then goes through each name in args and prints a greeting.

Why Use *args?

If you don’t know in advance how many arguments will be passed to your function, *args lets you handle any number of them.

Example:

Python

def add_numbers(*args): return sum(args) # Now you can pass any number of arguments to add up print(add_numbers(1, 2, 3))

print(add_numbers(1, 2, 3, 4, 5))

# Output:
6

# Output:
15

**kwargs: For Any Number of Keyword Arguments

Think of **kwargs as a way to handle multiple keyword arguments. Keyword arguments are just arguments with a name and value, like name="Alice".

How **kwargs Works

  • When you write **kwargs in a function, it gathers all extra keyword arguments into a dictionary.
  • You can call it kwargs or anything you like (e.g., **details), but **kwargs is the usual name.

Example:

Python

def display_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") # Call the function with different keyword arguments display_info(name="Alice", age=25, job="Engineer")

Output:

makefile

name: Alice age: 25 job: Engineer

Explanation:

  • **kwargs collects name="Alice", age=25, and job="Engineer" into a dictionary called kwargs.
  • The function then goes through each key-value pair and prints them.

Why Use **kwargs?

If your function might need to handle various named arguments that you don’t know ahead of time, **kwargs is the way to go.

Example:

Python

def make_sandwich(**kwargs): print("Sandwich with:") for ingredient, amount in kwargs.items(): print(f" - {amount} of {ingredient}") make_sandwich(bread="2 slices", cheese="1 slice", lettuce="a handful", mayo="a spread")

Output:

markdown

Sandwich with: - 2 slices of bread - 1 slice of cheese - a handful of lettuce - a spread of mayo

Using Both *args and **kwargs Together

You can use *args and **kwargs in the same function to allow for both unlimited positional and keyword arguments.

Order matters: If you’re using both, the order should be *args first, then **kwargs.

Example:

Python

def introduce(greeting, *args, **kwargs): print(greeting) for name in args: print(f"Hello, {name}!") for key, value in kwargs.items(): print(f"{key}: {value}") introduce("Welcome!", "Alice", "Bob", age=25, city="New York")

Output:

vbnet

Welcome! Hello, Alice! Hello, Bob! age: 25 city: New York

Explanation:

  • greeting is a normal argument.
  • *args captures "Alice" and "Bob" as a tuple of names.
  • **kwargs captures age=25 and city="New York" as a dictionary.

Using *args and **kwargs to Unpack Arguments

You can also use *args and **kwargs when calling a function to unpack a list, tuple, or dictionary into arguments.

Example with *args Unpacking a List or Tuple

Python

def add_three_numbers(a, b, c): return a + b + c numbers = (1, 2, 3) print(add_three_numbers(*numbers))

# Output:
6

Example with **kwargs Unpacking a Dictionary

Python

def print_person(name, age): print(f"{name} is {age} years old.") person_info = {"name": "Alice", "age": 25} print_person(**person_info)

# Output:
Alice is 25 years old.

In both examples:

  • *args or **kwargs in the function call unpacks the list/tuple or dictionary into separate arguments.

Quick Summary

  • *args: Collects multiple positional arguments into a tuple.
    • Use it when you don’t know how many positional arguments will be passed.
  • **kwargs: Collects multiple keyword arguments into a dictionary.
    • Use it when you don’t know how many keyword arguments will be passed.
  • Both Together: Allows for maximum flexibility by accepting any number of both positional and keyword arguments.

No comments:

Post a Comment

Recursion in DSA using Python

Follow me If you want to understand with  Graphical Representation   click on it. You can find the explanatory video at the bottom of this p...