Python variable length arguments
Created By: chatGPT
In Python, you can handle variable-length arguments using args and kwargs. The args is used for passing a variable number of non-keyword arguments to a function, while kwargs lets you pass a variable number of keyword arguments. Here's how you can use them:
def my_function(*args, **kwargs):
print('Positional arguments:', args)
print('Keyword arguments:', kwargs)
When you call
my_function
, you can pass any number of positional and keyword arguments. Here's an example:my_function(1, 2, 3, name='Alice', age=30)
# Output:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 30}
The args is treated as a tuple, while kwargs is treated as a dictionary. This means you can easily loop through them in your function. For example, you can do the following:
def my_function(*args, **kwargs):
for arg in args:
print('Arg:', arg)
for key, value in kwargs.items():
print(f'Key: {key}, Value: {value}')
Now, if you call the function again, you will see how it handles each argument:
my_function(1, 2, 3, name='Alice', age=30)
# Output:
# Arg: 1
# Arg: 2
# Arg: 3
# Key: name, Value: Alice
# Key: age, Value: 30
You can also combine regular parameters with *args and **kwargs. For example:
def my_function(a, b, *args, **kwargs):
print('a:', a)
print('b:', b)
print('Other positional args:', args)
print('Keyword args:', kwargs)
Call the function with fixed and variable arguments:
Using variable-length arguments can make your functions more flexible and dynamic, allowing you to handle a wide range of input scenarios.my_function(10, 20, 30, 40, name='Alice', age=30)
# Output:
# a: 10
# b: 20
# Other positional args: (30, 40)
# Keyword args: {'name': 'Alice', 'age': 30}