What are *args and **kwargs in Python?
*args lets a function accept any number of positional arguments, which arrive as a tuple. **kwargs lets it accept any number of keyword arguments (name=value), which arrive as a dictionary.
def show(*args, **kwargs):
print(args)
print(kwargs)
show(1, 2, name="Robin", age=20)
Output:
Tutorials Class - Output Window
(1, 2)
{'name': 'Robin', 'age': 20}
The names args and kwargs are only a habit. The stars are what matter. They are useful when you do not know in advance how many values will be passed, for example in a function that adds any amount of numbers.
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4))
Output:
Tutorials Class - Output Window
10
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |