Understanding *args and **kwargs in Python
By @bekbrace
Hey there, Python enthusiasts! In this post, we'll break down two fascinating features: *args and **kwargs. Whether you're a beginner looking to understand the basics or an experienced developer needing a refresher, this guide is for you. I’ve also included a video where I explain everything in more detail.
Watch the Video!
For a more detailed explanation, watch my video where I dive into code samples and real-world scenarios to help you get comfortable with these Python (awesome as I like always to say!) features.
Why *args and **kwargs Matter
Python's flexibility in handling function arguments is one of its many strengths. *args and **kwargs allow you to write functions that can accept a variable number of arguments, making them more adaptable and reusable.
What are *args?
*args lets you pass multiple positional arguments into a function. These arguments are then stored as a tuple that can be iterated through.
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Alice", "Bob", "Charlie")
RESULT:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
How *args and **kwargs Work Together
You can combine both in a single function for maximum flexibility. The order should always be *args, then **kwargs.
def profile(*skills, **details):
print("Skills:")
for skill in skills:
print(f" - {skill}")
print("\nDetails:")
for key, value in details.items():
print(f"{key}: {value}")
profile("Python", "Django", name="Amir", experience="5 years")
RESULT:
Skills:
- Python
- Django
Details:
name: Amir
experience: 5 years
When to Use Them
*args: When a function needs to accept an undetermined number of positional arguments.
**kwargs: When a function requires flexibility in the names and quantity of keyword arguments.
Both: When a function could benefit from flexibility with both positional and named arguments.
Conclusion
Python's *args and **kwargs are indispensable tools that can make your functions more dynamic and versatile. Experiment with them and see how they can simplify your coding life.
Got questions? Leave them in the comments :)
𝕏: https://www.twitter.com/bekbrace
IG: https://www.instagram.com/bek_brace
Top comments (7)
The first result is a wrong copy pasta :)
Other than that its a quick shrot explanation and usefull for beginners
where ?
The first result in your post?
Sorry but the result of the code you have in the code below is wrong!
Thanks but i am not a beginner at all and this is just confusing beginners that really have no idea...
you're right, an honest mistake - thanks man.
I deleted my comment, cause it's a bit stupid from my side :D
thanks again !
TIL :)