Bird
Raised Fist0
Pythonprogramming~10 mins

Variable-length arguments (*args) in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Variable-length arguments (*args)
Function called with arguments
*args collects all extra positional arguments
Inside function, args is a tuple of those arguments
Function uses args as needed
Function returns or ends
When a function is called with extra positional arguments, *args collects them into a tuple inside the function for flexible use.
Execution Sample
Python
def greet(*args):
    for name in args:
        print(f"Hello, {name}!")

greet('Alice', 'Bob', 'Charlie')
This function greets any number of people by printing a hello message for each name passed.
Execution Table
StepActionargs valueLoop variable 'name'Output
1Function greet called with ('Alice', 'Bob', 'Charlie')('Alice', 'Bob', 'Charlie')
2Start loop over args('Alice', 'Bob', 'Charlie')
3First iteration: name = 'Alice'('Alice', 'Bob', 'Charlie')AliceHello, Alice!
4Second iteration: name = 'Bob'('Alice', 'Bob', 'Charlie')BobHello, Bob!
5Third iteration: name = 'Charlie'('Alice', 'Bob', 'Charlie')CharlieHello, Charlie!
6Loop ends, function ends('Alice', 'Bob', 'Charlie')
💡 All names in args processed, loop ends, function returns None
Variable Tracker
VariableStartAfter 1After 2After 3Final
args()('Alice', 'Bob', 'Charlie')('Alice', 'Bob', 'Charlie')('Alice', 'Bob', 'Charlie')('Alice', 'Bob', 'Charlie')
nameAliceBobCharlie
Key Moments - 3 Insights
Why is args a tuple and not a list?
In the execution_table rows 1-5, args is shown as a tuple because *args always collects extra positional arguments into a tuple, which is immutable and fixed in size.
What happens if no arguments are passed to greet()?
If no arguments are passed, args is an empty tuple, so the loop in rows 2-5 does not run, and the function ends immediately as shown in exit_note.
Can we access args like a normal variable inside the function?
Yes, as shown in rows 3-5, args behaves like a tuple variable holding all extra arguments, so we can loop over it or index it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of 'name'?
ACharlie
BBob
CAlice
Dargs tuple
💡 Hint
Check the 'Loop variable name' column at step 3 in execution_table
At which step does the function finish processing all names?
AStep 6
BStep 4
CStep 5
DStep 2
💡 Hint
Look at the exit_note and the last step in execution_table
If greet() is called with no arguments, what will args be?
AAn empty list []
BAn empty tuple ()
CNone
DA string ''
💡 Hint
Refer to key_moments explanation about args when no arguments are passed
Concept Snapshot
def function_name(*args):
    # args is a tuple of all extra positional arguments
    for item in args:
        # use item

*args lets you pass any number of positional arguments to a function.
Inside, args is a tuple holding them all.
Full Transcript
This visual trace shows how Python functions use *args to accept any number of extra positional arguments. When the function greet is called with three names, these names are collected into the tuple args. The function then loops over args, assigning each name to the variable 'name' in turn, and prints a greeting. The variable tracker shows args stays the same tuple throughout, while 'name' changes each loop. Key moments clarify that args is always a tuple, even if empty, and can be used like any tuple inside the function. The quiz tests understanding of variable values at each step and what happens with no arguments.

Practice

(1/5)
1. What does *args do in a Python function?
easy
A. Allows the function to accept any number of extra positional arguments
B. Allows the function to accept only keyword arguments
C. Restricts the function to accept exactly one argument
D. Makes the function return multiple values

Solution

  1. Step 1: Understand the role of *args

    *args collects extra positional arguments passed to a function into a tuple.
  2. Step 2: Compare options with this behavior

    Only Allows the function to accept any number of extra positional arguments correctly describes this behavior; others describe different concepts.
  3. Final Answer:

    Allows the function to accept any number of extra positional arguments -> Option A
  4. Quick Check:

    *args = flexible positional inputs [OK]
Hint: Remember *args packs extra positions into a tuple [OK]
Common Mistakes:
  • Confusing *args with **kwargs
  • Thinking *args limits arguments
  • Assuming *args returns multiple values
2. Which of the following is the correct syntax to define a function that accepts variable-length positional arguments?
easy
A. def func(args*):
B. def func(*args):
C. def func(**args):
D. def func(args**):

Solution

  1. Step 1: Recall the syntax for variable-length positional arguments

    The correct syntax uses an asterisk before the parameter name: *args.
  2. Step 2: Match options with correct syntax

    def func(*args): matches the correct syntax; others are invalid or for different purposes.
  3. Final Answer:

    def func(*args): -> Option B
  4. Quick Check:

    Star before name = variable positional args [OK]
Hint: Use * before parameter name for variable positional args [OK]
Common Mistakes:
  • Using **args instead of *args
  • Placing * after the parameter name
  • Confusing syntax with keyword arguments
3. What is the output of the following code?
def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3, 4))
medium
A. 10
B. 1234
C. TypeError
D. None

Solution

  1. Step 1: Understand how *args works in the function

    The function collects all arguments into a tuple and sums them using sum().
  2. Step 2: Calculate the sum of the arguments

    1 + 2 + 3 + 4 = 10, so the function returns 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Sum of (1,2,3,4) = 10 [OK]
Hint: Sum all *args values to get total [OK]
Common Mistakes:
  • Concatenating numbers as strings
  • Expecting a TypeError for multiple args
  • Forgetting that *args is a tuple
4. Identify the error in this function definition:
def greet(*names):
    for name in names
        print(f"Hello, {name}!")
medium
A. print statement syntax error
B. Incorrect use of *args syntax
C. Missing colon after for loop
D. Function cannot have *args

Solution

  1. Step 1: Check the for loop syntax

    The for loop line is missing a colon at the end, which is required in Python.
  2. Step 2: Verify other parts of the function

    The *names syntax and print statement are correct; the function can have *args.
  3. Final Answer:

    Missing colon after for loop -> Option C
  4. Quick Check:

    For loops need a colon [:] [OK]
Hint: Check colons after for, if, while statements [OK]
Common Mistakes:
  • Forgetting colon after for loop
  • Confusing *args with **kwargs
  • Incorrect indentation
5. How can you write a function that accepts any number of positional arguments and returns a list of their squares?
hard
A. def squares(args): return [x**2 for x in args]
B. def squares(*args): return x**2 for x in args
C. def squares(**args): return [x**2 for x in args]
D. def squares(*args): return [x**2 for x in args]

Solution

  1. Step 1: Use *args to accept variable positional arguments

    The function parameter must be *args to accept any number of positional arguments.
  2. Step 2: Return a list of squares using list comprehension

    Use [x**2 for x in args] to square each argument and collect results in a list.
  3. Final Answer:

    def squares(*args): return [x**2 for x in args] -> Option D
  4. Quick Check:

    Use *args and list comprehension for squares [OK]
Hint: Use *args and list comprehension for flexible squares [OK]
Common Mistakes:
  • Using **args instead of *args
  • Forgetting to return a list
  • Incorrect comprehension syntax