【Python 学习笔记】 Variable-Length Positional Arguments (*args)

What is Variable-Length Positional Arguments (*args) in python?

In Python, Variable-Length Positional Arguments (often referred to as *args) allow a function to accept an arbitrary number of positional arguments. This makes the function flexible to handle cases where the number of inputs isn’t fixed or known beforehand.

The * symbol before args tells Python to gather any extra positional arguments into a tuple named args.

You can then iterate over or process args as needed, since it behaves like any other tuple.

Why Use *args?

  1. Flexibility: It allows a function to handle an unknown number of arguments, making it more adaptable.
  2. Conciseness: You don’t need to define multiple parameters if you’re unsure how many arguments you’ll receive.
def print_all(*args):
    for arg in args:
        print(arg)

print_all("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry

Common Scenarios for *args

1. Summing Multiple Numbers

def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3, 4))  # Output: 10
print(add_numbers(10, 20))      # Output: 30

2. Combine Strings

def combine_strings(*args):
    return " ".join(args)

# Example usage
print(combine_strings("Hello", "world", "from", "Python"))
# Output: Hello world from Python

3. Passing a Variable List of Names to Greet

def greet_people(greeting, *names):
    for name in names:
        print(f"{greeting}, {name}!")

greet_people("Hello", "Alice", "Bob", "Charlie")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!

4. Combining Lists

def combine_lists(*args):
    combined = []
    for lst in args:
        combined.extend(lst)
    return combined

print(combine_lists([1, 2], [3, 4], [5, 6]))  # Output: [1, 2, 3, 4, 5, 6]

Combining *args with Other Parameter Types

You can mix *args with other parameters, allowing you to enforce certain required arguments while accepting an arbitrary number of additional ones. The order in function definition is as follows:

  1. Regular positional arguments
  2. *args for variable-length positional arguments
  3. **kwargs for variable-length keyword arguments (if needed)
def example_function(required, *args, **kwargs):
    print("Required:", required)
    print("Args:", args)
    print("Kwargs:", kwargs)

example_function("Must have this", "extra1", "extra2", key1="value1", key2="value2")
# Output:
# Required: Must have this
# Args: ('extra1', 'extra2')
# Kwargs: {'key1': 'value1', 'key2': 'value2'}

Answers generated by OpenAI's ChatGPT with some editing.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值