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) — Accept Any Number of Inputs

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.


🎯 What Is *args?

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

💡 How *args Works

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

🎨 Real-World Example

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


🔧 Combining Regular Parameters with *args

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!
    pass

📊 *args Examples

Flexible Sum Function

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

Log Messages

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

Print Table

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

✅ Using *args with Loops

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: cherry

⚠️ Common Mistakes

Wrong: Trying to modify args as list

def 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

🔑 Key Takeaways

ConceptRemember
*argsAccept any number of positional arguments
TupleArguments are collected into a tuple
Loop throughUse for loops to access arguments
With parametersRegular params come BEFORE *args
FlexibilityFunctions work with 1, 5, or 100 arguments

🔗 What's Next?

Now let's explore lambda functions — quick, one-line functions!

Next: Lambda Functions →


Ready to practice? Try challenges or view solutions


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