Menu
CoddyTech

Comprehensions and Sorting

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

A comprehension combines a transformation, iteration, and optional filter into a new list. The Python expression shown corresponds to the C filtering loop, but constructs a list rather than printing each result. sorted returns a new list and accepts a key function such as len. It is stable: equal keys keep their original order. C qsort takes a comparison callback and does not promise stable ordering. Python list.sort sorts in place and returns None.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    int a[] = {3, -1, 2};
    for (int i = 0; i < 3; ++i) if (a[i] >= 0) printf("%d\n", a[i] * 2);
    return 0;
}

Python: complete example.py

values = [3, -1, 2]
print([v * 2 for v in values if v >= 0])
print(sorted(["pear", "fig", "plum"], key=len))

Watch the difference

Do not add an alphabetical tie-breaker when the contract says to preserve input order. key=len passes the function itself; key=len() tries to call it without an argument.

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 lowercase words from one line and a nonnegative minimum length from the next. Retain words meeting the minimum, including duplicates. Order them by increasing length and preserve input order for equal lengths. Print one word per line, or none if empty.

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

Python sorting is stable; C qsort does not promise stable equal-key ordering.

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