Python Args and Kwargs
Pass variable number of arguments to functions.
Flexible function arguments.
*args (Non-keyword Arguments)
```python def add_all(*args): return sum(args)
print(add_all(1, 2, 3)) # 6 print(add_all(1, 2, 3, 4, 5)) # 15 ```
**kwargs (Keyword Arguments)
```python def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
print_info(name="Tom", city="Austin", age=25) # name: Tom # city: Austin # age: 25 ```
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 ) # Name: Sarah # Hobbies: ('reading', 'gaming') # Details: {'city': 'Seattle', 'age': 28} ```
Unpacking
```python def greet(first, last): print(f"Hello {first} {last}!")
names = ["Tom", "Smith"] greet(*names) # Hello Tom Smith!
person = {"first": "Sarah", "last": "Johnson"} greet(**person) # Hello Sarah Johnson! ```
Remember
- *args for variable positional args - **kwargs for variable keyword args - Order: regular, *args, **kwargs