Variable Positional Arguments (args)

๐Ÿท๏ธ Functions / Args and Kwargs

๐Ÿง  Context Introduction

When you start writing functions in Python, you will quickly encounter situations where you don't know in advance how many arguments a function should accept. For example, imagine you need to calculate the total of an unknown number of server response times, or you want to log an unpredictable number of error messages. This is where variable positional arguments, commonly referred to as args, become incredibly useful. The term args is short for "arguments," and the asterisk (*) before it tells Python to pack all incoming positional arguments into a tuple.


โš™๏ธ What Are Variable Positional Arguments?

  • Variable positional arguments allow a function to accept any number of positional arguments.
  • They are defined using a single asterisk (*) followed by a parameter name, almost always written as *args.
  • Inside the function, args behaves like a tuple, meaning you can iterate over it, access elements by index, or check its length.
  • The name args is a convention, not a requirement. You could use *items or *values, but *args is widely recognized.

๐Ÿ› ๏ธ How to Define and Use *args

  • To define a function with variable positional arguments, place *args as the last parameter in the function definition.
  • When calling the function, you can pass zero, one, or many arguments, and they will all be collected into the args tuple.
  • Example of a function definition: def log_messages(*args):
  • Inside the function, you can loop through args using a for loop, or access individual items using index notation like args[0].

๐Ÿ“Š Comparison: Fixed Arguments vs. Variable Arguments

Feature Fixed Arguments Variable Arguments (*args)
Number of arguments expected Exactly defined in the function signature Any number (including zero)
How arguments are received As individual named variables As a single tuple
Flexibility Low โ€” you must know the count upfront High โ€” adapts to different callers
Use case When the number of inputs is always the same When the number of inputs varies

๐Ÿ•ต๏ธ Practical Example: Summing Unknown Number of Values

  • Imagine you need to write a function that sums up server response times, but the number of times varies per request.
  • Function definition: def calculate_total_time(*args):
  • Inside the function, you can initialize a variable total = 0 and then loop: for time in args: total += time
  • Finally, return the total.
  • When calling the function, you can do: calculate_total_time(120, 85, 200) or calculate_total_time(45, 67, 89, 102, 55).
  • The function works correctly regardless of how many arguments are passed.

๐Ÿงฉ Combining *args with Regular Parameters

  • You can mix regular (fixed) parameters with *args, but *args must come after all regular parameters.
  • Example function signature: def create_report(title, *args):
  • Here, title is a required argument, and any additional arguments are collected into args.
  • When calling: create_report("Server Errors", "Timeout", "Connection Refused", "Disk Full")
  • Inside the function, title holds the string "Server Errors", and args is a tuple containing ("Timeout", "Connection Refused", "Disk Full").

โš ๏ธ Important Rules and Best Practices

  • *args must always be placed after all regular positional parameters in the function definition.
  • You cannot define more than one *args parameter in a single function.
  • The *args parameter collects only positional arguments, not keyword arguments (those are handled by **kwargs).
  • Use *args when you genuinely do not know the number of inputs, but avoid overusing it if a fixed number of parameters makes the code clearer.
  • Always use the conventional name *args unless you have a strong reason to deviate, as it improves code readability for other engineers.

๐Ÿงช Testing Your Understanding

  • Try writing a function called print_names(*args) that prints each name on a new line.
  • Write a function multiply_all(*args) that returns the product of all numbers passed to it. If no numbers are passed, return 1.
  • Create a function build_url(base, *paths) that combines a base URL with multiple path segments. For example, build_url("https://example.com", "api", "v2", "users") should return a single string with segments joined by slashes.

๐Ÿ“Œ Summary

  • Variable positional arguments (*args) let your function accept any number of positional inputs.
  • The asterisk (*) packs arguments into a tuple named args.
  • They are ideal for situations where the number of inputs is unknown or varies.
  • Combine them with regular parameters by placing *args at the end.
  • Remember that args is just a tuple, so you can iterate, index, and measure it like any other tuple.

By mastering *args, you will write more flexible and reusable functions that adapt to different calling patterns โ€” a skill that becomes essential as you build more complex automation and data processing scripts.


Variable positional arguments (*args) allow a function to accept any number of positional arguments as a tuple.


๐ŸŸข Example 1: Basic variable positional arguments

Shows how to define a function that accepts any number of arguments.

def show_items(*args):
    print(args)

show_items("a", "b", "c")

๐Ÿ“ค Output: ('a', 'b', 'c')


๐ŸŸข Example 2: Accessing individual arguments by index

Demonstrates that args is a tuple and can be indexed.

def first_and_last(*args):
    first = args[0]
    last = args[-1]
    print("First:", first)
    print("Last:", last)

first_and_last(10, 20, 30, 40)

๐Ÿ“ค Output: First: 10 Last: 40


๐ŸŸข Example 3: Looping through all arguments

Shows how to iterate over all passed arguments.

def sum_all(*args):
    total = 0
    for number in args:
        total = total + number
    print(total)

sum_all(5, 10, 15)

๐Ÿ“ค Output: 30


๐ŸŸข Example 4: Mixing regular parameters with *args

Shows how to combine a fixed parameter with variable arguments.

def greet(greeting, *names):
    for name in names:
        print(greeting, name)

greet("Hello", "Alice", "Bob", "Charlie")

๐Ÿ“ค Output: Hello Alice Hello Bob Hello Charlie


๐ŸŸข Example 5: Practical use โ€” calculating average of any number of scores

Shows a real-world use case for engineers collecting variable data.

def average_score(*scores):
    total = 0
    count = 0
    for score in scores:
        total = total + score
        count = count + 1
    result = total / count
    print("Average:", result)

average_score(85, 90, 78, 92, 88)

๐Ÿ“ค Output: Average: 86.6


๐Ÿ“Š Comparison Table

Feature Without *args With *args
Number of arguments Fixed (must match definition) Any number (0 or more)
Data type received Individual variables Tuple
Flexibility Low โ€” must know count in advance High โ€” handles variable input
Example use case Adding exactly 2 numbers Adding any number of numbers

๐Ÿง  Context Introduction

When you start writing functions in Python, you will quickly encounter situations where you don't know in advance how many arguments a function should accept. For example, imagine you need to calculate the total of an unknown number of server response times, or you want to log an unpredictable number of error messages. This is where variable positional arguments, commonly referred to as args, become incredibly useful. The term args is short for "arguments," and the asterisk (*) before it tells Python to pack all incoming positional arguments into a tuple.


โš™๏ธ What Are Variable Positional Arguments?

  • Variable positional arguments allow a function to accept any number of positional arguments.
  • They are defined using a single asterisk (*) followed by a parameter name, almost always written as *args.
  • Inside the function, args behaves like a tuple, meaning you can iterate over it, access elements by index, or check its length.
  • The name args is a convention, not a requirement. You could use *items or *values, but *args is widely recognized.

๐Ÿ› ๏ธ How to Define and Use *args

  • To define a function with variable positional arguments, place *args as the last parameter in the function definition.
  • When calling the function, you can pass zero, one, or many arguments, and they will all be collected into the args tuple.
  • Example of a function definition: def log_messages(*args):
  • Inside the function, you can loop through args using a for loop, or access individual items using index notation like args[0].

๐Ÿ“Š Comparison: Fixed Arguments vs. Variable Arguments

Feature Fixed Arguments Variable Arguments (*args)
Number of arguments expected Exactly defined in the function signature Any number (including zero)
How arguments are received As individual named variables As a single tuple
Flexibility Low โ€” you must know the count upfront High โ€” adapts to different callers
Use case When the number of inputs is always the same When the number of inputs varies

๐Ÿ•ต๏ธ Practical Example: Summing Unknown Number of Values

  • Imagine you need to write a function that sums up server response times, but the number of times varies per request.
  • Function definition: def calculate_total_time(*args):
  • Inside the function, you can initialize a variable total = 0 and then loop: for time in args: total += time
  • Finally, return the total.
  • When calling the function, you can do: calculate_total_time(120, 85, 200) or calculate_total_time(45, 67, 89, 102, 55).
  • The function works correctly regardless of how many arguments are passed.

๐Ÿงฉ Combining *args with Regular Parameters

  • You can mix regular (fixed) parameters with *args, but *args must come after all regular parameters.
  • Example function signature: def create_report(title, *args):
  • Here, title is a required argument, and any additional arguments are collected into args.
  • When calling: create_report("Server Errors", "Timeout", "Connection Refused", "Disk Full")
  • Inside the function, title holds the string "Server Errors", and args is a tuple containing ("Timeout", "Connection Refused", "Disk Full").

โš ๏ธ Important Rules and Best Practices

  • *args must always be placed after all regular positional parameters in the function definition.
  • You cannot define more than one *args parameter in a single function.
  • The *args parameter collects only positional arguments, not keyword arguments (those are handled by **kwargs).
  • Use *args when you genuinely do not know the number of inputs, but avoid overusing it if a fixed number of parameters makes the code clearer.
  • Always use the conventional name *args unless you have a strong reason to deviate, as it improves code readability for other engineers.

๐Ÿงช Testing Your Understanding

  • Try writing a function called print_names(*args) that prints each name on a new line.
  • Write a function multiply_all(*args) that returns the product of all numbers passed to it. If no numbers are passed, return 1.
  • Create a function build_url(base, *paths) that combines a base URL with multiple path segments. For example, build_url("https://example.com", "api", "v2", "users") should return a single string with segments joined by slashes.

๐Ÿ“Œ Summary

  • Variable positional arguments (*args) let your function accept any number of positional inputs.
  • The asterisk (*) packs arguments into a tuple named args.
  • They are ideal for situations where the number of inputs is unknown or varies.
  • Combine them with regular parameters by placing *args at the end.
  • Remember that args is just a tuple, so you can iterate, index, and measure it like any other tuple.

By mastering *args, you will write more flexible and reusable functions that adapt to different calling patterns โ€” a skill that becomes essential as you build more complex automation and data processing scripts.

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

Variable positional arguments (*args) allow a function to accept any number of positional arguments as a tuple.


๐ŸŸข Example 1: Basic variable positional arguments

Shows how to define a function that accepts any number of arguments.

def show_items(*args):
    print(args)

show_items("a", "b", "c")

๐Ÿ“ค Output: ('a', 'b', 'c')


๐ŸŸข Example 2: Accessing individual arguments by index

Demonstrates that args is a tuple and can be indexed.

def first_and_last(*args):
    first = args[0]
    last = args[-1]
    print("First:", first)
    print("Last:", last)

first_and_last(10, 20, 30, 40)

๐Ÿ“ค Output: First: 10 Last: 40


๐ŸŸข Example 3: Looping through all arguments

Shows how to iterate over all passed arguments.

def sum_all(*args):
    total = 0
    for number in args:
        total = total + number
    print(total)

sum_all(5, 10, 15)

๐Ÿ“ค Output: 30


๐ŸŸข Example 4: Mixing regular parameters with *args

Shows how to combine a fixed parameter with variable arguments.

def greet(greeting, *names):
    for name in names:
        print(greeting, name)

greet("Hello", "Alice", "Bob", "Charlie")

๐Ÿ“ค Output: Hello Alice Hello Bob Hello Charlie


๐ŸŸข Example 5: Practical use โ€” calculating average of any number of scores

Shows a real-world use case for engineers collecting variable data.

def average_score(*scores):
    total = 0
    count = 0
    for score in scores:
        total = total + score
        count = count + 1
    result = total / count
    print("Average:", result)

average_score(85, 90, 78, 92, 88)

๐Ÿ“ค Output: Average: 86.6


๐Ÿ“Š Comparison Table

Feature Without *args With *args
Number of arguments Fixed (must match definition) Any number (0 or more)
Data type received Individual variables Tuple
Flexibility Low โ€” must know count in advance High โ€” handles variable input
Example use case Adding exactly 2 numbers Adding any number of numbers