Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
Why Functions?Parameters & ArgumentsReturn StatementsScopeDefault ParametersVariable Arguments (*args)Lambda FunctionsDecoratorsFunctional ProgrammingBest Practices
Python/Functions/Variable Arguments

πŸ“¦ Variable Arguments (*args) β€” Flexible Positional Parameters

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()`.


🎯 How *args Works

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))                # 10

How *args Works Internally

The `*` 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)

πŸ”§ Combining with Required Parameters

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 items

The key rule: regular parameters must come BEFORE *args

# βœ… Correct
def func(required, *args):
    pass

# ❌ Error - positional after *args
def func(*args, required):
    pass

πŸ’‘ Real-World Examples

Calculator with Average

Functions 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.0

Flexible Logger

def 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")

Database Query Builder

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 users

🎨 Processing *args

Unpacking Within Function

def 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)

With Type Hints

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.0

⚠️ Common Patterns and Gotchas

Empty *args is Valid

def count_items(*items):
    return len(items)

print(count_items())          # 0 - valid!
print(count_items(1))         # 1
print(count_items(1, 2, 3))   # 3

*args is Always a Tuple

def 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']

Unpacking Lists in Calls

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)

πŸš€ Advanced Patterns

Decorator with *args

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)

Method Forwarding

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

πŸ”‘ Key Takeaways

ConceptRemember
*argsCapture variable positional arguments
TupleArguments collected into tuple
OrderRegular parameters before *args
AccessIndex or loop through args
UnpackingUse `*list` to unpack in calls
Empty validFunction works with zero *args

πŸ”— What's Next?

Now let's learn about **kwargs β€” accepting variable keyword arguments!

Next: Keyword Arguments (**kwargs) β†’


Ready to practice? Try advanced challenges


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn