Python Interview > Explain *args and **kwargs in python > Flashcards
general summary
In Python, *args and **kwargs are often used to pass a variable number of arguments to a function.
*args collects a variable number of positional arguments into a tuple
**kwargs does the same for keyword arguments into a dictionary.
*args
Variable Number of Positional Arguments
How it Works: The name *args is a convention. The asterisk (*) tells Python to put any remaining positional arguments it receives into a tuple.
Use-Case: When the number of arguments needed is uncertain.
def sum_all(*args):
result = 0
for num in args:
result += num
return result
print(sum_all(1, 2, 3, 4)) # Output: 10**kwargs
Variable Number of Keyword Arguments
How it Works: The double asterisk (**) is used to capture keyword arguments and their values into a dictionary.
Use-Case: When a function should accept an arbitrary number of keyword arguments.
def print_values(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Keyword arguments are captured as a dictionary
print_values(name="John", age=30, city="New York")
# Output:
# name: John
# age: 30
# city: New York