Menu
CoddyTech

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

Practice on your own: Online Python compiler