Menu
CoddyTech

Pointers, Copies, and Aliases

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

Copying a C struct duplicates its fields, including pointer values. It does not clone pointed-to allocations. Python list.copy likewise creates an independent outer list while sharing its elements. Mutating the shared nested list is visible through both outer lists; appending to only the copied outer list is not. Plain assignment b = a would share the outer list too. Python references keep objects alive, so a local name going out of scope does not by itself leave a dangling alias.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    int value = 1;
    struct Box { int *p; };
    struct Box a = {&value}; struct Box b = a;
    *b.p = 9;
    printf("%d\n", *a.p);
    return 0;
}

Python: complete example.py

a = [[1]]
b = a.copy()
b[0][0] = 9
print(a)
print(sorted({3, 1, 3}))

Watch the difference

A Python set stores unique hashable values, but its iteration order is not a sorted-output contract. Use sorted for deterministic presentation. Empty braces create a dictionary; set() creates an empty set. del removes a binding or entry, not necessarily the object.

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 initial, replacement, and extra integers in [-20,20]. The scaffold makes a nested list, an alias, and a shallow copy. Through the alias replace the inner integer. Append [extra] only to the outer copy. Output the original nested list, the copy, and a sorted list of the three distinct input values, each on its own line.

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

As when copying a C struct containing a pointer, a shallow Python copy still shares nested objects.

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