Comprehensions and Sorting
Lesson 20 of 48 in Coddy's Python for JavaScript Developers course.
Transform selected values into a new list and sort results without accidentally losing the original collection.
JavaScript
const values = [3, -2, 1];
const doubled = values.filter(x => x > 0).map(x => x * 2);
const ordered = [...doubled].sort((a, b) => a - b);
console.log(ordered.join(" "));Python
values = [3, -2, 1]
doubled = [x * 2 for x in values if x > 0]
ordered = sorted(doubled)
print(*ordered)What changes
Both examples print 2 6. Read the comprehension as: visit each value, keep it if the condition passes, then evaluate the expression for that value. The result is a new list. The * in this example passes list elements separately to print; call unpacking is covered later. Python sorted returns a new list, while list.sort() changes the original and returns None. JavaScript array sorting mutates and returns the array, so assigning its result does not transfer safely. Python sorts numbers numerically by default. Use key=len to sort strings by length: the key function receives one item and supplies its comparison value. Equal keys retain their previous order. Tuples compare their first elements, then later elements to break ties.
Common mistake
A key function is not a two-argument JavaScript comparator. Pass the function itself, such as len, rather than calling it without an item. Keep complex branching in an ordinary loop instead of forcing it into one comprehension.
Your task
Filter words by a minimum length and use stable sorting to preserve input order among equal lengths.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler