Mastering *args and **kwargs in Python — A Simple Guide
Mastering *args
and **kwargs
in Python — A Simple Guide
By Code with AS
When writing functions in Python, sometimes you don’t know in advance how many arguments you’ll need to handle. That’s where *args
and **kwargs
come in.
These two features make your functions flexible and powerful. Let’s break them down with examples and clear explanations.
📌 What is *args
?
The *args
parameter lets you pass a variable number of positional arguments to a function. All values are collected into a tuple.
✅ Example:
💡 What’s happening?
-
The function
add
accepts any number of arguments:1
,4
, and5
. -
These are stored as a tuple:
(1, 4, 5)
. -
The built-in
sum()
function adds them all up and returns10
.
This is perfect when you don't know how many numbers a user might input.
📌 What is **kwargs
?
The **kwargs
parameter allows you to pass a variable number of keyword arguments — i.e., named arguments. These are collected into a dictionary.
✅ Example:
💡 What’s happening?
-
The function
print_info
accepts keyword arguments likename="Abcd"
andage=25
. -
These are stored as a dictionary:
{'name': 'Abcd', 'age': 25}
. -
The
for
loop goes through each key-value pair and prints it:
This is incredibly useful when passing configurations, user data, or any labeled values.
🚀 Why Use *args
and **kwargs
?
-
✅ Build more flexible functions.
-
✅ Accept optional or unknown numbers of arguments.
-
✅ Avoid rigid function definitions.
-
✅ Write cleaner and more reusable code.
Comments
Post a Comment