
Python
Use `*args` to accept any number of positional arguments. The asterisk unpacks all extra arguments into a tuple, enabling functions to work with varying input counts. This is fundamental to creating flexible, user-friendly APIs similar to built-in functions like `print()` and `sum()`.
The `*args` syntax captures all extra positional arguments into a tuple. The asterisk operator unpacks the arguments, and `args` becomes a tuple containing all of them. This enables variadic functionsβfunctions that accept different numbers of arguments.
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
print(sum_all(10)) # 10The `*` unpacks all extra arguments into a tuple:
def print_args(*args):
print(f"args type: {type(args)}")
print(f"args value: {args}")
print_args(1, 2, 3)
# Output:
# args type: <class 'tuple'>
# args value: (1, 2, 3)You can mix regular parameters with `*args`. Required parameters come first, then `*args` captures the rest.
def describe(category, *items):
print(f"Category: {category}")
print(f"Items: {items}")
print(f"Count: {len(items)}")
describe("fruits") # No items
describe("fruits", "apple") # One item
describe("fruits", "apple", "banana") # Multiple itemsThe key rule: regular parameters must come BEFORE *args
# β
Correct
def func(required, *args):
pass
# β Error - positional after *args
def func(*args, required):
passFunctions like average calculators benefit from accepting any number of values. They compute a statistic across a variable number of inputs.
def calculate_average(*numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
print(calculate_average(85, 90, 78, 92)) # 86.25
print(calculate_average(95, 88, 91, 87, 89)) # 90.0def log_event(level, *messages):
"""Log event with multiple message parts."""
full_message = " ".join(str(m) for m in messages)
print(f"[{level.upper()}] {full_message}")
log_event("info", "Server", "started", "successfully")
log_event("error", "Connection", "failed:", "timeout")def select_columns(table, *columns):
"""Build SQL SELECT statement."""
if not columns:
columns = ("*",)
column_list = ", ".join(columns)
return f"SELECT {column_list} FROM {table}"
print(select_columns("users")) # SELECT * FROM users
print(select_columns("users", "id", "name")) # SELECT id, name FROM usersdef process_data(*values):
"""Process variable number of values."""
print(f"Received {len(values)} values")
# Access by index
if values:
first = values[0]
rest = values[1:]
print(f"First: {first}, Rest: {rest}")
# Iterate
for i, val in enumerate(values):
print(f" [{i}] {val}")
process_data(10, 20, 30)from typing import Union
def add_numbers(*numbers: Union[int, float]) -> Union[int, float]:
"""Add any number of numbers."""
return sum(numbers)
print(add_numbers(1, 2, 3, 4, 5)) # 15
print(add_numbers(1.5, 2.5, 3.0)) # 7.0def count_items(*items):
return len(items)
print(count_items()) # 0 - valid!
print(count_items(1)) # 1
print(count_items(1, 2, 3)) # 3def modify(*args):
args.append("new") # β Error! Tuples don't have append()
# Solution: Convert to list if you need mutability
def modify(*args):
items = list(args) # β
Convert to list
items.append("new")
return items
print(modify(1, 2, 3)) # [1, 2, 3, 'new']You can unpack lists when calling functions with *args:
def add(*numbers):
return sum(numbers)
values = [1, 2, 3, 4, 5]
print(add(*values)) # Unpacks list: add(1, 2, 3, 4, 5)def timing_wrapper(func):
def wrapper(*args):
import time
start = time.time()
result = func(*args)
elapsed = time.time() - start
print(f"Took {elapsed:.4f} seconds")
return result
return wrapper
@timing_wrapper
def slow_function(*values):
import time
time.sleep(0.1)
return sum(values)
result = slow_function(1, 2, 3, 4, 5)class DataProcessor:
def process(self, operation, *values):
"""Forward to operation handlers."""
if operation == "sum":
return sum(values)
elif operation == "multiply":
result = 1
for v in values:
result *= v
return result
else:
return None
processor = DataProcessor()
print(processor.process("sum", 1, 2, 3)) # 6
print(processor.process("multiply", 2, 3, 4)) # 24| Concept | Remember |
|---|---|
| *args | Capture variable positional arguments |
| Tuple | Arguments collected into tuple |
| Order | Regular parameters before *args |
| Access | Index or loop through args |
| Unpacking | Use `*list` to unpack in calls |
| Empty valid | Function works with zero *args |
Now let's learn about **kwargs β accepting variable keyword arguments!
Next: Keyword Arguments (**kwargs) β
Ready to practice? Try advanced challenges
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward