Variable-length arguments (*args) in Python - Time & Space Complexity
When using variable-length arguments, the function can take many inputs. We want to know how the time to run changes as the number of inputs grows.
How does the function's work increase when we add more arguments?
Analyze the time complexity of the following code snippet.
def sum_all(*args):
total = 0
for num in args:
total += num
return total
This function adds up all the numbers given as arguments.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each argument in
argsto add it. - How many times: Once for each argument passed to the function.
As we add more numbers to add, the function does more work, going through each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of inputs.
Time Complexity: O(n)
This means the time to add all numbers grows in a straight line as you add more numbers.
[X] Wrong: "Using *args makes the function run instantly no matter how many inputs."
[OK] Correct: Even with *args, the function still needs to look at each input once, so more inputs mean more work.
Understanding how variable inputs affect time helps you explain your code clearly and shows you think about efficiency, a skill valued in many coding situations.
"What if we changed the function to multiply all arguments instead of adding? How would the time complexity change?"