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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler