Master the use of *args and **kwargs in Python functions with this beginner-friendly guide. Learn how to handle arbitrary positional and keyword arguments, combine them, and apply unpacking with practical examples and coding exercises. Perfect for students and new Python programmers.
*args
)**kwargs
)*args
and **kwargs
*args
)These allow a function to take any number of positional arguments. Inside the function, *args
collects all the positional arguments as a tuple.
Example:
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Ali", "Hamza", "Ahmad")
Output:
Hello, Ali!
Hello, Hamza!
Hello, Ahmad!
In this example, the greet
function can take any number of names. The *names
collects them into a tuple (names
), which can be iterated over.
**kwargs
)These allow a function to accept any number of keyword arguments (arguments passed as key-value pairs). Inside the function, **kwargs
collects these as a dictionary.
Example:
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Ali", age=25, city="Multan")
Output:
name: Ali
age: 25
city: Multan
In this case, the function accepts any number of keyword arguments and collects them into a dictionary (info
), which you can then work with inside the function.
*args
and **kwargs
You can also use both *args
and **kwargs
in the same function to handle a combination of positional and keyword arguments.
Example:
def display_data(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
display_data(1, 2, 3, name="Ali", age=25)
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Ali', 'age': 25}
Key Points:
*args
collects all positional arguments into a tuple.**kwargs
collects all keyword arguments into a dictionary.*args
and **kwargs
together to handle any type of arguments passed to a function.Based on the *args and **kwargs overview from the page you shared, here are beginner-friendly coding tasks to help solidify understanding of these concepts:
sum_all(*nums)
that returns the sum of any passed numbers.Example:
def sum_all(*nums):
return sum(nums)
print(sum_all(1, 2, 3, 4)) # Should print 10
construct_profile(**kwargs)
that returns a user info dictionary.Example:
def construct_profile(**kwargs):
return kwargs
profile = construct_profile(name="Ayesha", age=30, profession="Engineer")
print(profile)
log(*args, **kwargs)
that prints each positional argument and each key-value pair on separate lines.Example:
def log(*args, **kwargs):
for a in args:
print(f"ARG: {a}")
for k, v in kwargs.items():
print(f"KWARG: {k} = {v}")
log(10, 20, user="Ali", status="active")
*
and **
Example:
def multiply(a, b, c):
print(a * b * c)
nums = [2, 3, 4]
multiply(*nums) # Unpacks to multiply(2,3,4)
def print_person(name, age, city):
print(f"{name}, {age}, from {city}")
info = {"name": "Sara", "age": 28, "city": "Lahore"}
print_person(**info)
Tutorials, Roadmaps, Bootcamps & Visualization Projects