lapply and Comprehensions
Lesson 20 of 48 in Coddy's Python for R Developers course.
R often expresses element transformations with lapply, vapply, or vectorized operations. Python list comprehensions build lists by evaluating an expression for each selected element. Built-in Python lists do not perform R-style elementwise arithmetic: multiplication repeats the sequence, and addition concatenates lists. Python sorted returns a new list and accepts a one-argument key function. R order returns a permutation of indexes, while sort returns sorted values. Python sorting is stable, so equal keys retain their encounter order. Keep an explicit tie rule if a cross-language algorithm depends on that order.
R
values <- c(2, 4)
cat(values * 2, "\n")
cat(order(c(9, 3)), "\n")Python
words = ['pear', 'fig', 'apple']
print(sorted([word for word in words if len(word) >= 4], key=len))Porting trap
Translate vectorized intent, not operator spelling. Use a comprehension for elementwise multiplication of a Python list.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler