*args and **kwargs
3 min read ·
*args and **kwargs are used in Python functions to accept a variable number of arguments.*args→ handles multiple positional arguments**kwargs→ handles multiple keyword arguments
They make functions flexible and dynamic.
*args (Arbitrary Positional Arguments)
What is *args?
*args allows a function to receive any number of positional arguments.Inside the function,
*args is treated as a tuple.Basic Syntax of *args
Simple *args Example
Looping Through *args
*args with Normal Parameters
Note
Normal parameters must come before *args.
**kwargs (Arbitrary Keyword Arguments)
What is **kwargs?
**kwargs allows a function to accept any number of keyword arguments.Inside the function,
**kwargs is treated as a dictionary.Basic Syntax of **kwargs
Simple **kwargs Example
Looping Through **kwargs
**kwargs with Normal Parameters
Using *args and **kwargs Together
Caution
Order must be:
- Normal parameters
*args**kwargs
Passing List to *args
Passing Dictionary to **kwargs
Common Mistakes with *args and **kwargs
Using Wrong Order ❌
Treating *args as List ❌
Stop
*args is a tuple and cannot be modified.
Real World Example
Real World Scenario
Student marks system using *args and profile data using **kwargs
Exercise
Practice Task
- Create a function using
*argsto calculate sum - Create a function using
**kwargsto print user profile - Use both
*argsand**kwargsin one function - Pass list and dictionary using unpacking