Introduction
Sometimes you want a function to accept any number of inputs. *args lets you do that easily.
Jump into concepts and practice - no test required
Sometimes you want a function to accept any number of inputs. *args lets you do that easily.
def function_name(*args): # args is a tuple of all extra arguments for item in args: print(item)
*args collects extra positional arguments into a tuple.
You can use any name instead of args, but *args is the common style.
def greet(*args): for name in args: print(f"Hello, {name}!") greet('Alice', 'Bob')
def add_numbers(*args): total = 0 for num in args: total += num return total print(add_numbers(1, 2, 3, 4))
*args is a tuple containing all extra arguments.def show_args(*args): print(args) show_args('apple', 'banana', 'cherry')
This program prints details about a pet. You can add as many details as you want.
def describe_pet(*args): print("Pet details:") for detail in args: print(f"- {detail}") describe_pet('Name: Buddy', 'Type: Dog', 'Age: 5')
You can combine *args with regular parameters, but *args must come last.
Inside the function, args behaves like a tuple, so you can loop over it or access items by index.
*args lets functions accept any number of extra positional arguments.
These arguments are collected into a tuple inside the function.
This makes your functions flexible and able to handle different input sizes.
*args do in a Python function?*args*args collects extra positional arguments passed to a function into a tuple.*args = flexible positional inputs [OK]*args.def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3, 4))*args works in the functionsum().def greet(*names):
for name in names
print(f"Hello, {name}!")*names syntax and print statement are correct; the function can have *args.*args to accept variable positional arguments*args to accept any number of positional arguments.[x**2 for x in args] to square each argument and collect results in a list.