Array Callbacks and Keys
Lesson 20 of 48 in Coddy's Python for GDScript Developers course.
Godot Array.filter and map accept Callables, and sort_custom compares two elements. Python comprehensions combine filtering and transformation, while sorted accepts a one-element key function. Python sorting is stable and returns a new list; list.sort mutates and returns None. Godot's sort_custom does not promise a stable tie order, so a portable report should specify tie rules explicitly.
GDScript
extends SceneTree
func _init():
var words = ["pear", "fig", "plum"]
var kept = words.filter(func(w): return w.length() >= 4)
kept.sort()
print(" ".join(kept))
quit()Python
words = ["pear", "fig", "plum"]
kept = [word for word in words if len(word) >= 4]
print(*sorted(kept, key=len))Porting trap
Do not paste a two-argument Godot comparator into Python key. The key callable receives one element. For multiple ordering fields, return a tuple of keys.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler