Menu
CoddyTech

From LINQ to Comprehensions

Lesson 20 of 48 in Coddy's Python for C# Developers course.

Build and sort a filtered list while preserving tie order.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

var words = new[] { "pear", "fig", "plum" };
var result = System.Linq.Enumerable.Where(words, w => w.Length >= 4);
foreach (var word in result) Console.WriteLine(word);

Python

words = ["pear", "fig", "plum"]
result = [word for word in words if len(word) >= 4]
for word in result:
    print(word)

What changes

A list comprehension eagerly constructs a list; a typical LINQ Where query is deferred until enumeration. sorted(values, key=len) returns a new stable ordering; equal keys retain encounter order. list.sort changes an existing list and returns None. Python lambda expressions are introduced later; built-in len already works as a key function.

Transfer mistake

C# List<T>.Sort is not stable, while Python sorting is. Do not add an alphabetical tie-break when the contract wants original order.

Your task

Read lowercase words on one line and a nonnegative minimum length on the next. Retain words meeting that length, including duplicates. Sort by increasing length and preserve encounter order for ties. Output each retained word on its own line, or none if the result is empty. Parsing is supplied.

challenge icon

Challenge

Beginner

Read lowercase words on one line and a nonnegative minimum length on the next. Retain words meeting that length, including duplicates. Sort by increasing length and preserve encounter order for ties. Output each retained word on its own line, or none if the result is empty. Parsing is supplied.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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 C# Developers

Practice on your own: Online Python compiler