*args & **kwargs

*args

purpose

It allows a function to accept any number of positional arguments.

syntax

the * unpacks a sequence of arguments into individual elements.

how it works

Arguments passed to *args are collected into a tuple.

the tuple will look something like,

(“Alice”, “Bob”, “Charlie”)

use case

when you don’t know how many positional arguments will be passed.

def greet(*args):
    for name in args:
        print(f"Hello, {name}!")

greet("Alice", "Bob", "Charlie")

'''
OUTPUT
Hello Alice
Hello Bob
Hello Charlie
'''

**kwargs

purpose

allows a function to accept any number of keyword arguments.

syntax

the ** unpacks a dictionary of key-value pairs.

how it works

arguments passed to **kwargs are collected into a dictionary.

the dictionary will look like,

{“name” : ”Alice, "age": 30, "job": "Engineer"}

use case

when you want to handle names arguments dynamically.

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

greet(name="Alice", age=30, job="Engineer")

'''
OUTPUT
name: Alice
age: 30
job: Engineer
'''
Updated on