Variable Length Positional Arguments in Python

UpComing SoftWare Training Demos

🚀 *Gen AI Engineer Telugu (Production Focused)*
🗓️ *Date:* 30th Sept 2026, 07:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
🗓️ *Date:* 30th Sept 2026, 08:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/7r
👥 *Join WA Community:*
https://www.vlrt.in/7w
💡*Course Content:*
https://www.vlrt.in/7c
▶️ *Demo Videos:*
https://www.vlrt.in/7v

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 30th Sept 2026, 09:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

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

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • For loop 13 and 14th class

    The range() Function in Python The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times. Basic Syntax There are three ways to use range(): 1. range(stop) – One Parameter Form Generates numbers from 0 up to (but not including) the stop value. python for i in range(5):…

  • For Loop in Python

    A for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or any other iterable object. Unlike a while loop that runs as long as a condition is true, a for loop runs a specific number of times—once for each item in the sequence. The…

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

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

Leave a Reply

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