Master the Art of Flexible Functions with Python's *args and **kwargs ????
Elshad Karimov
Founder of AppMillers | Oracle ERP Fusion Cloud Expert | Teaching more than 200k people How to Code.
Python’s *args and **kwargs offer flexibility and dynamism in your code, allowing you to work with a varying number of arguments in your functions. Let’s dive into these magical constructs! ??
1?? *args: Handling a variable number of non-keyword (positional) arguments. *args is used to pass a variable number of non-keyword (positional) arguments to a function. It allows you to pass any number of positional arguments, which are then bundled into a tuple.
Example:
def sum_numbers(*args):
result = 0
for num in args:
result += num
return result
print(sum_numbers(1, 2, 3, 4)) # Output: 10
2?? **kwargs: Handling a variable number of keyword arguments. **kwargs is used to pass a variable number of keyword arguments to a function. It allows you to pass any number of keyword arguments, which are then bundled into a dictionary.
Example:
def display_user_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_user_info(name="John", age=30, city="New York")
Output:
name: John
age: 30
city: New York
3?? Combining *args and **kwargs: You can use *args and **kwargs in the same function to accept any combination of positional and keyword arguments:
def combined_example(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
combined_example(1, 2, 3, a=4, b=5, c=6)
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'a': 4, 'b': 5, 'c': 6}
Embrace the power of *args and **kwargs in your Python code to create more flexible, dynamic, and reusable functions! ??