Menu
CoddyTech

Indexes Without Pointer Math

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

In C you often keep an index beside an array and its length. Python enumerate supplies index/value pairs, with an optional starting index for presentation. This avoids manual counter updates and bounds calculations. Iterating a dictionary directly yields keys; items supplies key/value pairs for unpacking. Updating an existing key preserves its insertion position, so frequency output can follow first-seen order without maintaining a separate array of keys.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    const char *names[] = {"oak", "elm"};
    for (int i = 0; i < 2; ++i) printf("%d %s\n", i + 1, names[i]);
    return 0;
}

Python: complete example.py

for position, name in enumerate(["oak", "elm"], start=1):
    print(position, name)

Watch the difference

Do not confuse dictionary iteration with iterating a C struct layout. Dictionary entries are logical key/value pairs, not exposed byte offsets. Avoid adding or removing dictionary keys during iteration.

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

Split the one input line into lowercase labels; it may contain no labels. Print each label with its one-based position, separated by a single space. Then print counts and, for every distinct label in first-seen order, its label and frequency separated by a space. Empty input prints only counts.

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

Unlike a hand-maintained C lookup array, a Python dict already retains first insertion order.

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