0
0
Pythonprogramming~5 mins

Variable-length arguments (*args) in Python

Choose your learning style9 modes available
Introduction

Sometimes you want a function to accept any number of inputs. *args lets you do that easily.

When you want to add many numbers but don't know how many in advance.
When you want to print a list of items without fixing the count.
When you want to pass extra information to a function without changing its main inputs.
When you want to collect multiple values into one parameter for easy handling.
Syntax
Python
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.

Examples
This function greets any number of people given as arguments.
Python
def greet(*args):
    for name in args:
        print(f"Hello, {name}!")

greet('Alice', 'Bob')
This function adds all numbers passed to it and returns the sum.
Python
def add_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(add_numbers(1, 2, 3, 4))
This shows that *args is a tuple containing all extra arguments.
Python
def show_args(*args):
    print(args)

show_args('apple', 'banana', 'cherry')
Sample Program

This program prints details about a pet. You can add as many details as you want.

Python
def describe_pet(*args):
    print("Pet details:")
    for detail in args:
        print(f"- {detail}")

describe_pet('Name: Buddy', 'Type: Dog', 'Age: 5')
OutputSuccess
Important Notes

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.

Summary

*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.