Menu
CoddyTech

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

Practice on your own: Online Python compiler