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

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Python Input Function: A Beginner’s Guide with Examples

    The input() function in Python is used to take user input from the keyboard. It allows your program to interact with the user by prompting them to enter data, which can then be used in your code. By default, the input() function returns the user’s input as a string. Syntax of input() python Copy input(prompt) Key Points About input() Basic Examples of input() Example…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • Class Variables Andmethds

    Class Variables Class variables are variables that are shared by all instances of a class. They are defined directly within the class but outside of any method. Unlike instance variables, which are unique to each object, a single copy of a class variable is shared among all objects of that class. They are useful for…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

Leave a Reply

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