Back To Python Basics: *args & **Kwargs

Bek Brace - May 11 - - Dev Community

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")
Enter fullscreen mode Exit fullscreen mode

RESULT:

Hello, Alice!
Hello, Bob!
Hello, Charlie!
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

RESULT:

Skills:
 - Python
 - Django

Details:
name: Amir
experience: 5 years
Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .