Menu
CoddyTech

Tuples and Struct Values

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

A C struct groups named fields and can be copied by value. A Python tuple groups positional objects without a new type declaration. Unpacking binds those elements to names; the number of targets must match unless a starred target absorbs extras. Python evaluates the right side before assigning the left, allowing the swap shown here. A one-element tuple needs a comma, as in (3,). The tuple cannot replace its elements, but a contained list can still mutate.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    struct Point { int x; int y; };
    struct Point p = {3, 8};
    int x = p.x, y = p.y, temp = x; x = y; y = temp;
    printf("%d %d\n", x, y);
    return 0;
}

Python: complete example.py

point = (3, 8)
x, y = point
x, y = y, x
print(x, y)

Watch the difference

Tuple immutability does not recursively freeze the referenced objects. A C struct containing a pointer also copies that pointer value rather than duplicating the allocation it points to.

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

challenge icon

Challenge

Beginner

Read horizontal and vertical integer coordinates in [-100,100]. The scaffold stores them as point, a tuple. Unpack and swap the coordinates, then output the original tuple and swapped tuple on separate lines in Python tuple format.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

A tuple is positional, unlike a C struct with named fields. Swapping names does not mutate the original tuple.

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

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
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