Menu
CoddyTech

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

Practice on your own: Online Python compiler