Args and Kwargs
Args and Kwargs
Sometimes you do not know how many values a function will receive.
Python gives two tools for flexible functions:
*args**kwargs
What Is *args?
*args collects extra positional arguments into a tuple.
Positional arguments are values passed by position.
Basic Example
def add_all(*args):
print(args)
add_all(1, 2, 3)
Output
(1, 2, 3)
Sum Example
def add_all(*args):
total = 0
for num in args:
total += num
print(total)
add_all(5, 10, 15)
Output
30
What Is **kwargs?
**kwargs collects extra keyword arguments into a dictionary.
Keyword arguments use names.
Basic Example
def show_info(**kwargs):
print(kwargs)
show_info(name="Tom", age=25)
Output
{'name': 'Tom', 'age': 25}
Loop Through kwargs
def show_info(**kwargs):
for key, value in kwargs.items():
print(key, value)
show_info(name="Sara", city="Toronto")
Output
name Sara
city Toronto
Use Both Together
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, name="Tom", score=90)
Output
(1, 2)
{'name': 'Tom', 'score': 90}
Why These Matter
They help you build:
- flexible functions
- reusable tools
- wrappers
- decorators
- configuration functions
Naming Note
You can use other names, but args and kwargs are the common style.
Example:
def test(*numbers, **data):
pass
Code Along
Create a function that multiplies all numbers using *args.
Mini Challenge
Create a function:
profile(*args, **kwargs)
Tasks:
- Print all values in
args - Print all keys and values in
kwargs
Run:
profile("Admin", "Active", name="Maya", country="Canada")
Expected output:
Admin
Active
name Maya
country Canada
Real World Use Case
Frameworks and libraries use *args and **kwargs for flexible APIs, decorators, and configuration.
Quiz
- What does
*argscollect? - What does
**kwargscollect? - Is
argsa list or tuple? - Why are these useful?
Assignment
Create a function that prints the largest number from any amount of *args.
Summary
You learned how *args and **kwargs make functions flexible by accepting many values.