This Python *args / **kwargs lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
*args gathers extra positional arguments into a tuple. **kwargs gathers extra keyword arguments into a dict.
Use them when the function should accept a changing number of inputs, such as a row of skills plus a few named details.
Example 1: Start here
The names args and kwargs are a convention. The stars are the feature.
def report(*skills, **details): # define the function; it runs when you call it
print(skills)
print(details["city"])
report("Python", "SQL", city="Chennai") # call the function
Example 2: Collect extra positions
*scores gathers every positional argument into a tuple.
def total(*scores): # define the function; it runs when you call it
return sum(scores) # send this value back to the caller
print(total(70, 80, 90))
Example 3: Collect extra names
**info gathers named arguments into a dictionary.
def show(**info): # define the function; it runs when you call it
print(info["city"])
show(city="Chennai", seats=24) # call the function
Example 4: Pass them onward
A star in the call unpacks a list into separate arguments.
def total(*scores): # define the function; it runs when you call it
return sum(scores) # send this value back to the caller
values = [70, 80, 90] # a list; the values stay in this order
print(total(*values))
