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

  1. *args collects all positional arguments into a tuple
  2. It must come after regular positional arguments
  3. You can use any name after * (like *numbers*items) but *args is convention
  4. It allows functions to be more flexible and generic
  5. 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!

Similar Posts

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • Variable Length Keyword Arguments in Python

    Variable Length Keyword Arguments in Python Variable length keyword arguments allow a function to accept any number of keyword arguments. This is done using the **kwargs syntax. Syntax python def function_name(**kwargs): # function body # kwargs becomes a dictionary containing all keyword arguments Simple Examples Example 1: Basic **kwargs python def print_info(**kwargs): print(“Information received:”, kwargs) print(“Type of…

Leave a Reply

Your email address will not be published. Required fields are marked *