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

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • Escape Sequences in Python

    Escape Sequences in Python Escape sequences are special character combinations that represent other characters or actions in strings. Here’s a complete list of Python escape sequences with two examples for each: 1. \\ – Backslash python print(“This is a backslash: \\”) # Output: This is a backslash: \ print(“Path: C:\\Users\\Name”) # Output: Path: C:\Users\Name 2. \’ – Single quote…

Leave a Reply

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