Senior
What are *args and **kwargs in Python?
sobes.tech AI
Answer from AI
In Python, *args and **kwargs are used to pass a variable number of arguments to a function.
*argscollects positional arguments into a tuple.**kwargscollects named arguments into a dictionary.
This allows writing functions that accept any number of arguments.
Example:
def func(*args, **kwargs):
print('Positional arguments:', args)
print('Named arguments:', kwargs)
func(1, 2, 3, a=4, b=5)
Output:
Positional arguments: (1, 2, 3)
Named arguments: {'a': 4, 'b': 5}
This is useful for creating generic interfaces, proxying calls, and extending functionality without changing the function signature.