Menu
CoddyTech

Iterators and Comprehensions

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

Rust iterator adaptors remain lazy until consumed, often by collect. Python list comprehensions eagerly build a list, combining an expression, a for clause, and an optional if filter. A parenthesized generator expression is lazy instead. Python sorted returns a new list and supports a key function. list.sort mutates and returns None. Both Python sorting and Rust sort_by_key are stable; do not substitute Rust sort_unstable_by_key when equal-key encounter order matters.

Rust excerpt inside main

let words = ["pear", "fig", "plum"];
let mut result: Vec<_> = words.iter().copied().filter(|w| w.len() >= 4).collect();
result.sort_by_key(|w| w.len());
println!("{}", result.join(","));

Python

words = ["pear", "fig", "plum"]
result = sorted([w for w in words if len(w) >= 4], key=len)
print(result)

Porting trap

Rust string length counts UTF-8 bytes; Python string length counts Unicode code points. The examples use ASCII so the comparison is deliberate. Neither length necessarily counts user-perceived graphemes.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

Read a line of lowercase words, then a nonnegative minimum length. Keep words whose length is at least the minimum, including duplicates. Sort them by increasing length, preserving original order for equal lengths. Print one word per line, or none if no words qualify. The supplied scaffold parses both input lines.

Your code goes in main.py. The locked driver.py starts your program 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 Rust Developers

Practice on your own: Online Python compiler