*args
: Positional Arguments
Think of *args
as a way to handle multiple positional arguments (those without a name, just like usual function arguments). Normally, functions have a fixed number of arguments, but with *args
, you can pass as many as you want!
How *args
Works
- When you write
*args
in a function, it gathers all extra positional arguments into a tuple. - You can call this
args
anything you want (e.g.,*numbers
), but by convention, we use*args
.
Example:
Output:
Explanation:
*args
takes"Alice"
,"Bob"
, and"Charlie"
and puts them in a tuple calledargs
.- The function then goes through each name in
args
and prints a greeting.
Why Use *args
?
If you don’t know in advance how many arguments will be passed to your function, *args
lets you handle any number of them.
Example:
**kwargs
: For Any Number of Keyword Arguments
Think of **kwargs
as a way to handle multiple keyword arguments. Keyword arguments are just arguments with a name and value, like name="Alice"
.
How **kwargs
Works
- When you write
**kwargs
in a function, it gathers all extra keyword arguments into a dictionary. - You can call it
kwargs
or anything you like (e.g.,**details
), but**kwargs
is the usual name.
Example:
Output:
Explanation:
**kwargs
collectsname="Alice"
,age=25
, andjob="Engineer"
into a dictionary calledkwargs
.- The function then goes through each key-value pair and prints them.
Why Use **kwargs
?
If your function might need to handle various named arguments that you don’t know ahead of time, **kwargs
is the way to go.
Example:
Output:
Using Both *args
and **kwargs
Together
You can use *args
and **kwargs
in the same function to allow for both unlimited positional and keyword arguments.
Order matters: If you’re using both, the order should be *args
first, then **kwargs
.
Example:
Output:
Explanation:
greeting
is a normal argument.*args
captures"Alice"
and"Bob"
as a tuple of names.**kwargs
capturesage=25
andcity="New York"
as a dictionary.
Using *args
and **kwargs
to Unpack Arguments
You can also use *args
and **kwargs
when calling a function to unpack a list, tuple, or dictionary into arguments.
Example with *args
Unpacking a List or Tuple
Example with **kwargs
Unpacking a Dictionary
In both examples:
*args
or**kwargs
in the function call unpacks the list/tuple or dictionary into separate arguments.
Quick Summary
*args
: Collects multiple positional arguments into a tuple.- Use it when you don’t know how many positional arguments will be passed.
**kwargs
: Collects multiple keyword arguments into a dictionary.- Use it when you don’t know how many keyword arguments will be passed.
- Both Together: Allows for maximum flexibility by accepting any number of both positional and keyword arguments.
No comments:
Post a Comment