Comprehensions and Sorting
Lesson 20 of 48 in Coddy's Python for Luau Developers course.
Python comprehensions eagerly build lists from transformation and filtering, while generator expressions are lazy. Luau commonly builds a result table in a loop. Python sorted returns a new list; list.sort mutates and returns None. Luau table.sort mutates and has no stability guarantee, whereas Python sorting preserves encounter order for equal keys. The source example uses alphabetical ordering of distinct ASCII words.
Luau 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 Luau 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 Luau Developers
1From Luau 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