Learn Python Programming  /  Functions  /  Lambda & Comprehensions

Lambda & Comprehensions

lambda creates small, throwaway functions in a single line, and comprehensions build new collections in a single line โ€” together they are how Python replaces a lot of what R does with the apply family.

lambda โ€” Anonymous Functions

A lambda is a small function without a name, written in a single expression - useful when you need a quick function just once, often as an argument to another function.

R Code
square = lambda x: x ** 2
print(square(5))

# equivalent full function, for comparison
def square2(x):
    return x ** 2
Output
25

Using lambda with sorted()

R Code
students = [("Rafi", 88), ("Meera", 92), ("Zayn", 76)]

sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
print(sorted_students)
Output
[('Meera', 92), ('Rafi', 88), ('Zayn', 76)]

map() and filter()

These are Python\'s closest equivalent to R\'s sapply() and vectorised filtering, though a comprehension is usually preferred for readability today.

R Code
nums = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

print(squared)
print(evens)
Output
[1, 4, 9, 16, 25]
[2, 4]
💡 Tip
The equivalent list comprehensions - [x**2 for x in nums] and [x for x in nums if x % 2 == 0] - do the exact same thing and are generally considered more readable than map()/filter() with a lambda. Most modern Python style guides prefer comprehensions.

List, Dict, and Set Comprehensions Side by Side

R Code
nums = [1, 2, 3, 4]

list_comp = [x**2 for x in nums]
dict_comp = {x: x**2 for x in nums}
set_comp  = {x % 2 for x in nums}   # only 2 unique remainders possible

print(list_comp)
print(dict_comp)
print(set_comp)
Output
[1, 4, 9, 16]
{1: 1, 2: 4, 3: 9, 4: 16}
{0, 1}

Advanced: Nested Comprehensions

🚀 Advanced Example
Comprehensions can be nested to flatten a list of lists in a single readable line.
R Code
matrix = [[1,2,3], [4,5,6], [7,8,9]]

flattened = [num for row in matrix for num in row]
print(flattened)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Key Points

  • lambda arg: expression creates a small, unnamed function, often passed directly into another function like sorted().
  • map() and filter() apply a function across a sequence, similar in spirit to R\'s sapply().
  • Comprehensions - [ ] for lists, { } for dicts and sets - are the idiomatic, usually preferred alternative to map()/filter().
  • Comprehensions can be nested to flatten or transform multi-level structures in one line.