Menu
CoddyTech

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 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 Dart Developers

Practice on your own: Online Python compiler