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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler