
Python
Sometimes you need to accept many arguments, but you don't know in advance how many the caller will provide. The `*args` feature lets you accept as many positional arguments as you want. Inside the function, all those arguments are collected into a tuple that you can loop through. This is incredibly useful for functions that need flexibility.
The `*args` syntax allows a function to accept any number of positional arguments after the required parameters. The asterisk tells Python "collect all these arguments into a tuple." Inside your function, `args` becomes a tuple containing all the extra arguments passed by the caller. This is perfect for functions like `print()` or `sum()` that work with varying numbers of inputs.
def add_many(*numbers):
total = 0
for num in numbers:
total += num
return total
print(add_many(1, 2, 3)) # 6
print(add_many(1, 2, 3, 4, 5)) # 15
print(add_many(10)) # 10The `*args` parameter collects all extra arguments into a tuple:
def show_items(*items):
print(f"Number of items: {len(items)}")
for item in items:
print(f" - {item}")
show_items("apple")
show_items("apple", "banana")
show_items("apple", "banana", "cherry", "date")Output:
Number of items: 1
- apple
Number of items: 2
- apple
- banana
Number of items: 4
- apple
- banana
- cherry
- datedef print_all(*items):
for item in items:
print(item)
print_all("apple")
print_all("apple", "banana")
print_all("apple", "banana", "cherry", "date")One function works with 1 item, 2 items, or 100 items!
You can mix regular parameters with `*args`:
def describe(item, *extras):
print(f"Item: {item}")
if extras:
print(f"Extras: {extras}")
describe("pizza")
describe("pizza", "pepperoni", "large")Important: Regular parameters come BEFORE `*args`:
def func(required, *args): # ✅ Correct
pass
def func(*args, required): # ❌ Wrong!
passdef sum_all(*numbers):
"""Add up any number of 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, 20, 30)) # 60def log_messages(*messages):
"""Log all messages."""
for msg in messages:
print(f"[LOG] {msg}")
log_messages("Server started")
log_messages("User logged in", "Profile loaded", "Dashboard ready")def print_row(*values):
"""Print values in a row."""
for val in values:
print(f"{val:15}", end="")
print() # New line
print_row("Name", "Age", "City")
print_row("Alice", "25", "NYC")
print_row("Bob", "30", "LA")Since `*args` creates a tuple, you can loop through it:
def process(*items):
for i, item in enumerate(items):
print(f"Item {i+1}: {item}")
process("apple", "banana", "cherry")
# Output:
# Item 1: apple
# Item 2: banana
# Item 3: cherrydef modify(*args):
args.append("new") # ❌ Error! Tuples don't have append()
# Solution: Convert to list if you need to modify
def modify(*args):
items = list(args) # ✅ Convert to list
items.append("new")
return items| Concept | Remember |
|---|---|
| *args | Accept any number of positional arguments |
| Tuple | Arguments are collected into a tuple |
| Loop through | Use for loops to access arguments |
| With parameters | Regular params come BEFORE *args |
| Flexibility | Functions work with 1, 5, or 100 arguments |
Now let's explore lambda functions — quick, one-line functions!
Ready to practice? Try challenges or view solutions
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