Collection Pipelines
Lesson 20 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin filter and sortedBy return new lists, much like a Python comprehension followed by sorted with a key. Kotlin sortBy mutates a mutable list; Python list.sort mutates and returns None. Python key functions, like sortedBy selectors, produce a key for one element. Use a tuple key to order by several fields. Stable sorting keeps encounter order for equal keys.
Kotlin
fun main() {
val words = listOf("pear", "fig", "plum")
println(words.filter { it.length >= 4 }.sortedBy { it.length }.joinToString(" "))
}Python
words = ["pear", "fig", "plum"]
kept = [word for word in words if len(word) >= 4]
print(*sorted(kept, key=len))Porting trap
Python lambda has an explicit parameter, not Kotlin's implicit it. A comprehension can combine filtering and transformation without allocating an intermediate map/filter pipeline.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler