Mastering *args and **kwargs in Python — A Simple Guide

 Mastering *args and **kwargs in Python — A Simple Guide

By Code with AS 


When writing functions in Python, sometimes you don’t know in advance how many arguments you’ll need to handle. That’s where *args and **kwargs come in.

These two features make your functions flexible and powerful. Let’s break them down with examples and clear explanations.



📌 What is *args?

The *args parameter lets you pass a variable number of positional arguments to a function. All values are collected into a tuple.

✅ Example:


def add(*numbers): return sum(numbers) print(add(1, 4, 5)) # Output: 10

💡 What’s happening?

  • The function add accepts any number of arguments: 1, 4, and 5.

  • These are stored as a tuple: (1, 4, 5).

  • The built-in sum() function adds them all up and returns 10.

This is perfect when you don't know how many numbers a user might input.


📌 What is **kwargs?

The **kwargs parameter allows you to pass a variable number of keyword arguments — i.e., named arguments. These are collected into a dictionary.

✅ Example:

def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Abcd", age=25)

💡 What’s happening?

  • The function print_info accepts keyword arguments like name="Abcd" and age=25.

  • These are stored as a dictionary: {'name': 'Abcd', 'age': 25}.

  • The for loop goes through each key-value pair and prints it:

    name: Abcd age: 25

This is incredibly useful when passing configurations, user data, or any labeled values.


🚀 Why Use *args and **kwargs?

  • ✅ Build more flexible functions.

  • ✅ Accept optional or unknown numbers of arguments.

  • ✅ Avoid rigid function definitions.

  • ✅ Write cleaner and more reusable code.


Thank you for reading. 

If you find my blogs informative and useful, please consider following me on 

GitHub (https://bit.ly/3ZFsW2E), 
and YouTube (https://bit.ly/3Jd0gss)

Like, Share, & Subscribe ]

Comments

Popular posts from this blog

10 DATA SCIENTIST INTERN INTERVIEW QUESTIONS WITH ANSWERS

GENERATE A QR CODE FOR RESUMES USING PYTHON

TECHNICAL CODING INTERVIEW QUESTIONS FOR A DATA ANALYST FRESHER