Python22 min read
Python Args and Kwargs
Learn *args and **kwargs clearly: how variable arguments work, how unpacking works, and how to design flexible APIs safely.
Michael Brown
September 10, 2025
5.5k209
In real projects, you often want functions that can accept:
- any number of positional values
- any number of keyword options
That is what:
- `*args` handles (positional arguments)
- `**kwargs` handles (keyword arguments)
## *args (variable positional arguments)
```python
def add_all(*args):
print(args) # shows it's a tuple
return sum(args)
print(add_all(1, 2, 3))
print(add_all(1, 2, 3, 4, 5))
```
Expected output:
```
(1, 2, 3)
6
(1, 2, 3, 4, 5)
15
```
## **kwargs (variable keyword arguments)
```python
def print_info(**kwargs):
print(kwargs) # shows it's a dictionary
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Tom", city="Austin", age=25)
```
Expected output:
```
{'name': 'Tom', 'city': 'Austin', 'age': 25}
name: Tom
city: Austin
age: 25
```
## Using both together
```python
def make_user(name, *hobbies, **details):
print(f"Name: {name}")
print(f"Hobbies: {hobbies}")
print(f"Details: {details}")
make_user(
"Sarah",
"reading", "gaming",
city="Seattle",
age=28
)
```
Expected output:
```
Name: Sarah
Hobbies: ('reading', 'gaming')
Details: {'city': 'Seattle', 'age': 28}
```
## Unpacking (very common in real code)
```python
def greet(first, last):
print(f"Hello {first} {last}!")
names = ["Tom", "Smith"]
greet(*names)
person = {"first": "Sarah", "last": "Johnson"}
greet(**person)
```
Expected output:
```
Hello Tom Smith!
Hello Sarah Johnson!
```
## Graph: argument flow
```mermaid
flowchart LR
A[Call site] --> B[*args tuple]
A --> C[**kwargs dict]
B --> D[Function receives arguments]
C --> D
```
## Best practice rule
Use `*args` and `**kwargs` to make APIs flexible, but do not use them to hide unclear function design.
If a function expects a specific argument, name it directly.
In the next lesson, you will learn type hints, which improves clarity and helps tools catch mistakes earlier.
#Python#Intermediate#Functions