where, map, and List Building
Lesson 20 of 48 in Coddy's Python for Dart Developers course.
Dart where and map commonly return lazy iterables; toList materializes them. A Python list comprehension eagerly builds a list, while a generator expression defers work. Python sorted returns a new list and accepts a one-argument key function. Dart List.sort mutates the list and takes a two-element comparator. Python list.sort also mutates, but returns None and uses the key-function model. Python sorting is stable; do not assume the same guarantee for Dart List.sort. Preserve a tie rule explicitly when a port must agree for equal sort keys.
Dart
void main() {
final words = ['pear', 'fig', 'apple'];
final kept = words.where((word) => word.length >= 4).toList();
kept.sort((a, b) => a.length.compareTo(b.length));
print(kept);
}Python
words = ['pear', 'fig', 'apple']
print(sorted([word for word in words if len(word) >= 4], key=len))Porting trap
A Dart comparator receiving two values is not a valid Python key callback. Use a one-value key such as len.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler