*args and **kwargs
Master flexible function arguments. Learn how to write functions that accept any number of inputs.
Master flexible function arguments. Learn how to write functions that accept any number of inputs. This hands-on tutorial focuses on practical implementation of *args and **kwargs concepts.
*args and **kwargs
Sometimes you don't know how many arguments will be passed to your function. Python allows you to handle this using *args and **kwargs.
*args (Arbitrary Arguments)
The * operator packs any number of positional arguments into a Tuple.
**kwargs (Arbitrary Keyword Arguments)
The ** operator packs any number of keyword arguments into a Dictionary.
Combining with Regular Parameters 🎯
You can mix regular parameters, *args, and **kwargs. The order is critical!
Order: required → defaults → *args → keyword-only → **kwargs
Forwarding Arguments to Other Functions 📤
A powerful pattern is to accept *args and **kwargs and pass them to another function.
Preview: Decorators 🎨
The forwarding pattern above is the foundation of decorators - a powerful Python feature you'll learn later.
Coding Challenge: Logger Function with Metadata 📝
Create a function log_event(event_name, *args, **kwargs) that:
- Prints the event name
- Prints all positional arguments
- Prints all keyword arguments as metadata
AI Mentor
Confused about "Python args and kwargs variable length arguments"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 5What data type does *args store arguments as?
Key Takeaways
✅ *args allows unlimited positional arguments (Tuple).
✅ **kwargs allows unlimited keyword arguments (Dictionary).
✅ Forwarding: Use func(*args, **kwargs) to pass arguments through.
✅ Decorators use this pattern to wrap functions.
What's Next?
In the next lesson, we'll learn about Lambda Functions - small, anonymous one-liners.
Keep coding! 🚀