2023年10月24日火曜日

What is variadic argument in Python?

 A variadic argument in Python is a function parameter that can accept a variable number of arguments. Variadic arguments are defined using the * operator before the parameter name. For example, the following function definition shows a variadic argument called *args:

Python
def print_args(*args):
  for arg in args:
    print(arg)

This function can be called with any number of arguments, and all of the arguments will be printed to the console. For example:

Python
print_args(1, 2, 3)

Output:

1
2
3

Variadic arguments can also be used to accept a variable number of keyword arguments. To do this, you use the ** operator before the parameter name. For example, the following function definition shows a variadic keyword argument called **kwargs:

Python
def print_kwargs(**kwargs):
  for key, value in kwargs.items():
    print(f"{key}: {value}")

This function can be called with any number of keyword arguments, and all of the keyword arguments will be printed to the console. For example:

Python
print_kwargs(name="Alice", age=25)

Output:

name: Alice
age: 25

Variadic arguments are a powerful feature of Python that can be used to write more flexible and reusable code.

Here are some examples of how to use variadic arguments in Python:

  • Write a function that can print any number of arguments to the console:
Python
def print_args(*args):
  for arg in args:
    print(arg)

print_args(1, 2, 3, "hello", "world!")

Output:

1
2
3
hello
world!
  • Write a function that can calculate the sum of any number of numbers:
Python
def sum_numbers(*numbers):
  sum = 0
  for number in numbers:
    sum += number
  return sum

print(sum_numbers(1, 2, 3, 4, 5))

Output:

15
  • Write a function that can create a dictionary from any number of keyword arguments:
Python
def create_dict(**kwargs):
  return kwargs

print(create_dict(name="Alice", age=25))

Output:

{'name': 'Alice', 'age': 25}

Variadic arguments can be a great way to make your Python code more flexible and reusable.

0 件のコメント:

コメントを投稿