Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Functions
  5. Packing and Unpacking Arguments

Packing and Unpacking Arguments

Packing refers to the process of collecting multiple function arguments into a single iterable object—like a tuple or dictionary—so they can be handled flexibly inside a function.

Thank you for reading this post, don't forget to subscribe!

1.) Packing with *args (Non-keyword Arguments):

  • *args allows a function to accept any number of positional (non-keyword) arguments. These arguments are packed into a tuple.

*args is used to pass a variable number of positional arguments to a function. Inside the function, they are accessible as a tuple.

Example:

def print_numbers(*args):
    print("Positional arguments:", args)

print_numbers(1, 2, 3, 4)

#output: Positional arguments: (1, 2, 3, 4)

2.) Packing with **kwargs (Keyword Arguments)

  • **kwargs allows a function to accept any number of keyword arguments (name-value pairs). These arguments are packed into a dictionary.

**kwargs is used to pass a variable number of keyword arguments to a function. Inside the function, they are accessible as a dictionary.

Example:

def print_details(**kwargs):
    print("Keyword arguments:", kwargs)

print_details(name="Alice", age=25, city="Delhi")


#output: Keyword arguments: {'name': 'Alice', 'age': 25, 'city': 'Delhi'}

Combined Example of Packing with *args and **kwargs:

def display_info(*args, **kwargs):
    print("Args:", args)
    print("Kwargs:", kwargs)

display_info(1, 2, 3, name="Alice", age=25)


#output: Args: (1, 2, 3)
         #Kwargs: {'name': 'Alice', 'age': 25}

Unpacking is the reverse of packing. It means breaking a collection like a list, tuple, or dictionary into individual elements and passing them as arguments.

1.) Unpacking Positional Arguments with *:

  • You can use * to unpack elements of a sequence like a tuple or list into separate positional arguments.

Example:

nums = (1, 2, 3)

def add(a, b, c):
    print(a + b + c)

add(*nums)  # Equivalent to add(1, 2, 3)

2.) Unpacking Keyword Arguments with **:

  • You can use ** to unpack a dictionary into individual keyword arguments.

Example:

details = {'name': 'Bob', 'age': 30}

def show(name, age):
    print(f"Name: {name}, Age: {age}")

show(**details)  # Equivalent to show(name='Bob', age=30)

How can we help?