0
0
PythonConceptBeginner · 3 min read

What is args in Python: Explanation and Examples

*args in Python is used in function definitions to allow passing a variable number of positional arguments as a tuple. It helps functions accept any number of inputs without explicitly defining each one.
⚙️

How It Works

Imagine you have a gift bag that can hold any number of small gifts. You don't know how many gifts will come, but you want to carry them all together. In Python, *args works like that gift bag for function inputs. When you define a function with *args, it collects all extra positional arguments into a tuple inside the function.

This means you can call the function with one, two, or many arguments, and *args will gather them all. Inside the function, you can treat args like a tuple of values to use as needed.

💻

Example

This example shows a function that adds any number of numbers given to it using *args.

python
def add_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(add_numbers(1, 2, 3))
print(add_numbers(5, 10, 15, 20))
Output
6 50
🎯

When to Use

Use *args when you want a function to accept any number of positional arguments without knowing how many in advance. This is useful for functions like summing numbers, printing messages, or handling flexible inputs.

For example, if you write a function to log messages, you might want to accept one or many messages without changing the function each time.

Key Points

  • *args collects extra positional arguments as a tuple.
  • It allows flexible function calls with varying numbers of inputs.
  • Inside the function, args behaves like a tuple you can loop over.
  • It must come after regular positional parameters in the function definition.

Key Takeaways

*args lets functions accept any number of positional arguments.
Arguments passed with *args are accessible as a tuple inside the function.
Use *args for flexible functions that handle varying inputs.
*args must be placed after regular parameters in function definitions.