Master Python Function Arguments: Positional, Keyword, Default, *args, **kwargs
This guide walks through ten Python function‑argument examples—including positional, keyword, default values, mutable‑default pitfalls, variable‑length *args and **kwargs, argument unpacking, ordering rules, and mutable‑object handling—providing clear code snippets and explanations for each case.
Example 1: Positional Arguments
def greet(name, age):
print(f"Hello, {name}, you are {age} years old.")
greet("Xiaoming", 20)Output: Hello, Xiaoming, you are 20 years old.
Explanation: Values are passed according to the order defined in the function signature.
Example 2: Keyword Arguments
def describe_pet(animal_type, pet_name):
print(f"This is a {animal_type}, named {pet_name}.")
describe_pet(pet_name="Wangcai", animal_type="dog")Output: This is a dog, named Wangcai.
Explanation: Arguments are passed using
key=valuesyntax, independent of order.
Example 3: Default Arguments
def say_hello(name="User"):
print(f"Hello, {name}!")
say_hello()
say_hello("Xiaohong")Outputs:
Hello, User!
Hello, Xiaohong!
Explanation: If no argument is supplied, the default value is used.
Example 4: Mutable Default Argument Pitfall
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item(1)) # Output: [1]
print(add_item(2)) # Output: [1, 2] ❗Problem!Explanation: The default list is created once at function definition, so subsequent calls share the same list.
Correct approach:
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
print(add_item(1)) # Output: [1]
print(add_item(2)) # Output: [2]Example 5: *args (Variable‑Length Positional Arguments)
def sum_numbers(*args):
print("Received arguments:", args)
print("Sum:", sum(args))
sum_numbers(1, 2, 3, 4)Output:
Received arguments: (1, 2, 3, 4)
Sum: 10
Explanation:
*argspacks multiple positional arguments into a tuple.
Example 6: **kwargs (Variable‑Length Keyword Arguments)
def show_info(**kwargs):
print("Received keyword arguments:", kwargs)
for key, value in kwargs.items():
print(f"{key}: {value}")
show_info(name="Zhang San", age=28, city="Beijing")Output:
Received keyword arguments: {'name': 'Zhang San', 'age': 28, 'city': 'Beijing'}
name: Zhang San
age: 28
city: Beijing
Explanation:
**kwargspacks multiple keyword arguments into a dictionary.
Example 7: Mixing *args and **kwargs
def demo_func(a, b, *args, **kwargs):
print("a:", a)
print("b:", b)
print("*args:", args)
print("**kwargs:", kwargs)
demo_func(1, 2, 3, 4, 5, name="Tom", age=22)Output:
a: 1
b: 2
*args: (3, 4, 5)
**kwargs: {'name': 'Tom', 'age': 22}
Explanation: A function can receive positional arguments, variable‑length positional arguments, keyword arguments, and variable‑length keyword arguments simultaneously.
Example 8: Argument Unpacking with * and **
def multiply(a, b, c):
return a * b * c
numbers = [2, 3, 4]
result = multiply(*numbers) # Unpack list
print(result) # Output: 24
info = {"a": 5, "b": 6, "c": 7}
result = multiply(**info) # Unpack dict
print(result) # Output: 210Explanation:
*unpacks sequences,
**unpacks dictionaries, enabling dynamic argument passing.
Example 9: Correct Parameter Order
def order_example(a, b, *args, keyword_only=True, **kwargs):
print("a:", a)
print("b:", b)
print("*args:", args)
print("keyword_only:", keyword_only)
print("**kwargs:", kwargs)
order_example(1, 2, 3, 4, keyword_only=False, name="Lucy")Output:
a: 1
b: 2
*args: (3, 4)
keyword_only: False
**kwargs: {'name': 'Lucy'}
Explanation: Parameter order matters: positional →
*args→ keyword‑only →
**kwargs.
Example 10: Modifying a Mutable Object Inside a Function
def modify_list(lst):
lst.append(99)
print("Inside function list:", lst)
my_list = [1, 2, 3]
modify_list(my_list)
print("Outside function list:", my_list)Output:
Inside function list: [1, 2, 3, 99]
Outside function list: [1, 2, 3, 99]
Explanation: Lists are mutable; changes inside the function affect the original object because Python uses a reference‑passing mechanism.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.