Menu
CoddyTech

Lists Versus C Arrays

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

A C array has a fixed number of contiguous elements of one type. A Python list is a growable sequence of object references, and its elements need not share a type. Indexes start at zero; a negative Python index counts from the end. A slice excludes its stop and creates a new shallow list. append changes the existing list and returns None. A bad Python index raises IndexError, whereas reading outside a C array is undefined behavior. A slice endpoint beyond the length is clipped.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    int values[] = {4, 8, 12};
    printf("%d\n", values[2]);
    return 0;
}

Python: complete example.py

values = [4, 8]
values.append(12)
print(values[-1])
print(values[:2])

Watch the difference

Python list assignment does not allocate an independent copy of the elements. A C pointer advanced into an array is a view of existing storage; a Python list slice creates a new outer container.

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

Four input lines contain integers in [-20,20]. Make a list of the first three, append the fourth, and remove index zero using pop(0). Print the removed value, the remaining last element, and a slice of the first two remaining elements on three lines. Use Python list formatting for the slice.

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

A Python slice creates a new outer list; a C pointer into an array still refers to the original storage.

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