Variable Length Positional Arguments in Python
Variable Length Positional Arguments in Python
Variable length positional arguments allow a function to accept any number of positional arguments. This is done using the *args syntax.
Syntax
python
def function_name(*args):
# function body
# args becomes a tuple containing all positional arguments
Simple Examples
Example 1: Basic *args
python
def print_numbers(*args):
print("Numbers received:", args)
print("Type of args:", type(args))
print("Total numbers:", len(args))
print("-" * 30)
print_numbers(1, 2, 3)
print_numbers(10, 20, 30, 40, 50)
print_numbers() # No arguments
Example 2: Sum of Any Numbers
python
def calculate_sum(*numbers):
total = sum(numbers)
print(f"Numbers: {numbers}")
print(f"Sum: {total}")
print("-" * 20)
calculate_sum(1, 2, 3) # Output: Sum: 6
calculate_sum(5, 10, 15, 20) # Output: Sum: 50
calculate_sum(2, 4, 6, 8, 10) # Output: Sum: 30
Example 3: Mixed with Regular Arguments
python
def student_info(name, age, *subjects):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Subjects: {subjects}")
print("-" * 25)
student_info("Alice", 15, "Math", "Science")
student_info("Bob", 16, "History", "English", "Art")
student_info("Charlie", 14) # No subjects
Practical Examples
Example 4: Shopping Cart
python
def add_to_cart(*items):
print("Items added to cart:")
for item in items:
print(f"- {item}")
print(f"Total items: {len(items)}")
print("-" * 20)
add_to_cart("Apple", "Banana")
add_to_cart("Book", "Pen", "Notebook", "Pencil")
add_to_cart("Milk") # Single item
Example 5: Grade Calculator
python
def calculate_average(student_name, *scores):
average = sum(scores) / len(scores) if scores else 0
print(f"Student: {student_name}")
print(f"Scores: {scores}")
print(f"Average: {average:.2f}")
print("-" * 25)
calculate_average("John", 85, 90, 78)
calculate_average("Sarah", 92, 88, 95, 87)
calculate_average("Mike", 75) # Only one score
Example 6: String Concatenation
python
def join_strings(*words):
result = " ".join(words)
print(f"Words: {words}")
print(f"Joined: '{result}'")
print("-" * 20)
join_strings("Hello", "world")
join_strings("I", "love", "Python", "programming")
join_strings("Single") # One word
Advanced Examples
Example 7: Mixed with Default Arguments
python
def create_sentence(start, *middle_words, end="."):
sentence = start + " " + " ".join(middle_words) + end
print(f"Sentence: {sentence}")
print("-" * 25)
create_sentence("Hello", "there", "how", "are", "you", end="?")
create_sentence("I", "am", "learning", "Python")
create_sentence("This", "is", "fun", end="!")
Example 8: Math Operations
python
def math_operations(operation, *numbers):
if operation == "add":
result = sum(numbers)
print(f"Sum of {numbers} = {result}")
elif operation == "multiply":
result = 1
for num in numbers:
result *= num
print(f"Product of {numbers} = {result}")
print("-" * 25)
math_operations("add", 1, 2, 3, 4)
math_operations("multiply", 2, 3, 4)
math_operations("add", 5, 10)
Example 9: Flexible Greeting Function
python
def greet(*names, greeting="Hello"):
if not names:
print(f"{greeting} everyone!")
else:
for name in names:
print(f"{greeting}, {name}!")
print("-" * 20)
greet("Alice", "Bob", "Charlie")
greet("John", greeting="Hi")
greet() # No names
Real-World Use Cases
Example 10: Logging System
python
def log_message(*messages, level="INFO"):
print(f"[{level}]", end=" ")
for message in messages:
print(message, end=" ")
print() # New line
print("-" * 30)
log_message("System", "started", "successfully")
log_message("Error", "occurred", "in", "module", level="ERROR")
log_message("Processing", "complete", level="DEBUG")
Example 11: Recipe Ingredients
python
def make_recipe(recipe_name, *ingredients):
print(f"Recipe: {recipe_name}")
print("Ingredients needed:")
for i, ingredient in enumerate(ingredients, 1):
print(f"{i}. {ingredient}")
print("-" * 25)
make_recipe("Pasta", "Spaghetti", "Tomato sauce", "Cheese")
make_recipe("Smoothie", "Banana", "Milk", "Honey", "Ice")
Key Points to Remember
*argscollects all positional arguments into a tuple- It must come after regular positional arguments
- You can use any name after
*(like*numbers,*items) but*argsis convention - It allows functions to be more flexible and generic
- You can have zero or many arguments
Benefits
- Flexibility: Functions can handle different numbers of inputs
- Clean code: No need to create multiple functions for different argument counts
- Versatility: Useful for wrapper functions, decorators, and utilities
Variable length arguments make your functions much more powerful and adaptable!