25. Understanding *args and **kwargs

Quiz: 0/5

In Python, *args and **kwargs allow you to create functions that accept a variable number of arguments. These are useful when you don't know beforehand how many arguments will be passed to your function. Let’s break down how each of these works and explore practical examples.

Arbitrary positional arguments (args)

The *args syntax allows you to pass a variable number of positional arguments to a function. These arguments are stored in a tuple, and you can access them by iterating over it. The key benefit is that you don’t need to specify the exact number of arguments in the function definition.

Example 1: Printing positional arguments

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

How it works:

  • *args collects all positional arguments passed to the function and stores them as a tuple.
  • You can loop through the tuple to access each argument.

Calling the function:

my_function(1, 2, 3)   
# Output: 
# 1
# 2
# 3

my_function("apple", "banana", "cherry")   
# Output: 
# apple
# banana
# cherry

Example 2: Summing numbers with *args

Suppose you want to create a function that sums any number of arguments:

def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3))        # Output: 6
print(sum_numbers(10, 20, 30, 40)) # Output: 100

How it works:

*args allows the function to handle any number of numerical arguments, making it adaptable to different inputs.

Arbitrary keyword arguments (kwargs)

The **kwargs syntax allows you to pass a variable number of keyword arguments to a function. These arguments are stored as a dictionary, where the keys are the argument names, and the values are the argument values.

Example 1: Printing keyword arguments

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

How it works:

  • **kwargs collects keyword arguments as a dictionary.
  • You can access each key-value pair in the dictionary.

Calling the function:

my_function(name="Alice", age=30, city="Paris")
# Output:
# name: Alice
# age: 30
# city: Paris

Example 2: Building a user profile with **kwargs

Let's create a function that accepts any number of user attributes and builds a profile.

def build_profile(**kwargs):
    profile = {}
    for key, value in kwargs.items():
        profile[key] = value
    return profile

user_profile = build_profile(name="Alice", age=30, job="Engineer")
print(user_profile)  # Output: {'name': 'Alice', 'age': 30, 'job': 'Engineer'}

How it works:

  • The function accepts any number of keyword arguments and stores them in a dictionary.
  • It allows for flexibility, as it can handle different or optional attributes.

Combining *args and kwargs

You can use both *args and **kwargs in the same function to accept both positional and keyword arguments. However, *args must come before **kwargs in the parameter list.

Example: Displaying information from both *args and **kwargs

def display_info(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

display_info(1, 2, 3, name="Alice", age=30)
# Output:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 30}

How it works:

  • The *args parameter captures all positional arguments as a tuple.
  • The **kwargs parameter collects keyword arguments as a dictionary.
  • Both are printed separately, allowing the function to handle a mix of argument types.

Summary

  • *args allows for a flexible number of positional arguments, accessible as a tuple.
  • **kwargs enables you to pass a variable number of keyword arguments, accessible as a dictionary.
  • You can combine both in a function to handle a wide range of arguments (positional and keyword).

These tools offer great flexibility in Python, making your functions more adaptable and scalable. You can use them to write functions that can accept a dynamic number of inputs, making your code cleaner and more reusable.

Hands-On Practise

Exercise: Create a Shopping Cart

Write a function called calculate_total that accepts multiple items (as positional arguments) and their corresponding prices (as keyword arguments). The function should return the total cost of the items in the cart.

Function Signature:

def calculate_total(*items, **prices):
    pass

Requirements:

  • The function should accept a list of item names as positional arguments.
  • The function should accept a dictionary of item prices using keyword arguments (where the key is the item name and the value is the price).
  • The function should calculate the total cost by adding up the prices of the items in the cart.

Challenge:

Modify the function to handle cases where some items might not have prices specified. In such cases, the item should be skipped, and no price should be added to the total.

Output:

Quizzes: 0/5

Question 1:

What is the purpose of *args in Python functions?

  • To pass a fixed number of positional arguments.
  • To pass a variable number of positional arguments.
  • To pass a variable number of keyword arguments.
  • To pass a fixed number of keyword arguments.

Question 2:

What does **kwargs in Python functions do?

  • It passes a fixed number of keyword arguments.
  • It collects positional arguments into a tuple.
  • It collects keyword arguments into a dictionary.
  • It allows a function to accept only one argument.

Question 3:

Can you combine *args and **kwargs in a function definition?

  • Yes, but *args must come after **kwargs.
  • No, they cannot be combined in the same function.
  • Yes, and *args must come before **kwargs.
  • Yes, but they can be used interchangeably.

Question 4:

What will happen if an item passed in *args is not found in **kwargs?

  • An error will be raised.
  • The function will skip that item and continue.
  • The item will be assigned a default value.
  • The function will stop execution.

Question 5:

What is the primary advantage of using *args and **kwargs in Python?

  • They make the function faster.
  • They allow for greater flexibility in function calls.
  • They reduce the number of arguments required.
  • They automatically validate the function parameters.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonDefault parameter valuesNext lessonVariable Scopes in Python