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

  • How to Use Python’s Print Function and Avoid Syntax and Indentation Errors

    1. Print Output to Console and String Manipulation Tips for the print() Function What is the print() Function? The print() function in Python is used to display output to the console. It is one of the most commonly used functions, especially for debugging and displaying results. Basic Usage Output: String Manipulation Tips for print() 1….

  • Object: Methods and properties

    🚗 Car Properties ⚙️ Car Methods 🚗 Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: ⚙️ Car Methods Methods are the verbs that describe what a car can do….

  • 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…

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

Leave a Reply

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