Menu
CoddyTech

Varargs Without va_list

Lesson 24 of 48 in Coddy's Python for C Developers course.

C variadic functions use an explicit agreement such as a count or format string to know which promoted argument types to read with va_arg. Python *values collects positional extras into a tuple; **options collects keyword extras into a dictionary. At a call site, * expands an iterable into positional arguments and ** expands a mapping with string keys into keyword arguments. The same punctuation collects in a definition and expands in a call.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int total(int count, ...) {
    va_list ap; va_start(ap, count); int result = 0;
    for (int i = 0; i < count; ++i) result += va_arg(ap, int);
    va_end(ap); return result;
}
int main(void) {
    printf("%d\n", total(3, 2, 4, 6));
    return 0;
}

Python: complete example.py

def total(*values, **options):
    return sum(values) * options.get("factor", 1)
print(total(*[2, 4, 6], **{"factor": 2}))

Watch the difference

Python does not require va_start or va_end, but it still rejects duplicate values for a named parameter. These stars are not pointer dereferences. Empty positional extras give an empty tuple whose sum is zero.

Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Implement scaled_total(*values, **options). Return the sum of integer values times options.get("factor", 1), ignoring other option names. Do not mutate inputs or print. The driver reads integer tokens (possibly none), then a factor, and prints results from an unpacked positional call and a call with unpacked factor options.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

Python collects positional extras into a tuple instead of requiring C va_list type bookkeeping.

Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

Try it yourself

from functions import scaled_total

values = [int(part) for part in input().split()]
factor = int(input())
print(scaled_total(*values))
print(scaled_total(*values, **{"factor": factor, "note": "ignored"}))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler