Python Interview Questions

32 Questions
Python

Python

Web DevelopmentFrontendBackendData Science

Question 14

What are *args and **kwargs in Python?

Answer:

In Python, *args and **kwargs are used in function definitions to allow for variable numbers of arguments to be passed to a function. They are very useful when you want to create flexible functions that can handle different numbers and types of arguments.

*args

  • Purpose: *args is used to pass a variable number of non-keyword arguments to a function.
  • Behavior: It allows you to pass any number of positional arguments, which are received as a tuple.

Example:

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

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

In this example, example_function can accept any number of positional arguments, which are collected into the tuple args.

**kwargs

  • Purpose: **kwargs is used to pass a variable number of keyword arguments to a function.
  • Behavior: It allows you to pass any number of keyword arguments, which are received as a dictionary.

Example:

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

example_function(name="Alice", age=30)
# Output:
# name: Alice
# age: 30

In this example, example_function can accept any number of keyword arguments, which are collected into the dictionary kwargs.

Using *args and **kwargs Together

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

Example:

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

example_function(1, 2, 3, name="Alice", age=30)
# Output:
# arg: 1
# arg: 2
# arg: 3
# name: Alice
# age: 30

In this example, example_function can handle both positional and keyword arguments, providing great flexibility in how the function is called.

Practical Use Cases

1. Wrapper Functions

When writing wrapper functions, *args and **kwargs allow you to pass arguments to the wrapped function without needing to explicitly define them.

def wrapper_function(func):
    def inner_function(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return inner_function

@wrapper_function
def say_hello(name, greeting="Hello"):
    print(f"{greeting}, {name}")

say_hello("Alice")
# Output:
# Before function call
# Hello, Alice
# After function call

2. Function Argument Forwarding

You can use *args and **kwargs to forward arguments from one function to another.

def forward_function(*args, **kwargs):
    another_function(*args, **kwargs)

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

forward_function("Bob", age=25)
# Output:
# Name: Bob, Age: 25

In this example, forward_function forwards its arguments to another_function, making it flexible in handling various inputs.

Summary

  • *args allows a function to accept any number of positional arguments, which are accessible as a tuple.
  • **kwargs allows a function to accept any number of keyword arguments, which are accessible as a dictionary.
  • You can use both *args and **kwargs together to create highly flexible functions that can handle a wide range of argument inputs.
  • These features are particularly useful in writing generic, reusable, and flexible code, especially for functions that need to handle varying numbers of arguments or when writing decorators and wrapper functions.

Recent job openings