args
(arguments)
In Python, *args
is a special syntax in function definitions that allows the function to accept an undetermined number of arguments. When you prefix an argument name with an asterisk (*
), that argument collects positional arguments into a tuple
.
This feature is particularly useful when you’re not sure how many arguments might be passed to a function. The name args
is just a convention. In practice, you can use any valid identifier after the asterisk, and using descriptive names is always recommended.
Using *args
makes your functions flexible and adaptable to different input sizes. It allows you to write functions that can handle a variety of input scenarios without needing to know in advance how many arguments a user will pass.
Example
Here’s a simple example of how you can use the *args
syntax in a Python function:
>>> def greet(*names):
... for name in names:
... print(f"Hello, {name}!")
...
>>> greet("Alice", "Bob", "Charlie")
Hello, Alice!
Hello, Bob!
Hello, Charlie!
In this example, the greet()
function can take any number of people’s names, and it will greet each one.
Related Resources
Tutorial
Python args and kwargs: Demystified
In this step-by-step tutorial, you'll learn how to use args and kwargs in Python to add more flexibility to your functions. You'll also take a closer look at the single and double-asterisk unpacking operators, which you can use to unpack any iterable object in Python.
For additional information on related topics, take a look at the following resources:
- Defining Your Own Python Function (Tutorial)
- Python args and kwargs: Demystified (Course)
- Python args and kwargs: Demystified (Quiz)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)