Comprehensions and Sorting
Lesson 20 of 48 in Coddy's Python for Lua Developers course.
Python list comprehensions combine transformation and filtering in one expression and eagerly build a new list. A generator expression is lazy. Lua usually builds a result table with a loop and table.insert. Python sorted returns a new list; list.sort mutates and returns None. Lua table.sort also mutates, but it does not guarantee stability. Python sorting is stable, so equal-key items preserve encounter order. The Lua example sorts distinct strings alphabetically rather than relying on equal-length stability.
Lua example
local result = {}
for _, w in ipairs({"pear", "fig", "plum"}) do
if #w >= 4 then table.insert(result, w) end
end
table.sort(result)
print(table.concat(result, ","))Python
words = ["pear", "fig", "plum"]
result = sorted([w for w in words if len(w) >= 4], key=len)
print(result)Porting trap
Python len on text counts code points, whereas Lua length counts bytes. Use ASCII when comparing these length filters without a Unicode library.
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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler