Menu
CoddyTech

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

Practice on your own: Online Python compiler