CodingNic

Generators, Iterators, and Decorators

Lambdas and Dates

Generators, Iterators, and Decorators 20 min read

Lambdas and Dates

Objectives

By the end of this chapter, you should be able to:

  • Create and use lambdas
  • Sort a list with sorted() and a key function
  • Manipulate dates and times using the datetime module

💡 Why this matters: Lambdas are the concise, throwaway functions you’ll pass to things like sorted(), map(), and filter() all the time. datetime is how you’ll handle any real-world data that involves a date or timestamp.

Lambdas

A lambda is the closest thing Python has to an anonymous, one-line function. It’s just a shorter way to write a small function you already know how to write with def:

python
def add_with_def(x, y):
    return x + y

add_with_lambda = lambda x, y: x + y

print(add_with_def(1, 2))     # 3
print(add_with_lambda(1, 2))  # 3

Both functions do the same thing. A lambda starts with the lambda keyword, followed by a comma-separated list of arguments, a colon, and a single expression that gets returned automatically (no return keyword needed). A few more:

python
double = lambda val: 2 * val
yell = lambda text: text.upper() + "!!!"

print(double(5))       # 10
print(yell("hello"))   # HELLO!!!

Lambdas are genuinely anonymous: every lambda’s __name__ is literally '<lambda>', no matter what variable you assign it to:

python
print(add_with_lambda.__name__)          # '<lambda>'
print(add_with_lambda.__name__ == double.__name__)  # True

Because of that, lambdas are best reserved for short, one-off functions, not anything you’ll want to reference or debug later by name.

Lambdas with map, filter, and reduce

Lambdas shine as throwaway arguments to map(), filter(), and reduce() (the last of which lives in the functools module as of Python 3):

python
from functools import reduce

numbers = [1, 2, 3, 4, 5]

print(reduce(lambda x, y: x + y, numbers))          # 15
print(list(map(lambda x: x * 2, numbers)))          # [2, 4, 6, 8, 10]
print(list(filter(lambda x: x * 2 > 5, numbers)))   # [3, 4, 5]

map transforms every element (here, doubling each one), filter keeps only the elements matching a condition (here, where doubling the number gives more than 5), and reduce combines every element down to a single value (here, summing them all).

Sorting with sorted() and key

You’ve already seen .sort(), which reorders a list in place. sorted() is the built-in function version: it takes any iterable and returns a new sorted list, leaving the original untouched:

python
numbers = [4, 1, 3, 2]
print(sorted(numbers))  # [1, 2, 3, 4]
print(numbers)          # [4, 1, 3, 2], unchanged

Both accept a key argument: a function that’s called on each element to decide what to sort by, instead of sorting the elements themselves. This is exactly where a lambda earns its keep:

python
words = ["banana", "fig", "kiwi", "watermelon"]
print(sorted(words, key=lambda w: len(w)))
# ['fig', 'kiwi', 'banana', 'watermelon']

Here, key=lambda w: len(w) tells sorted() to compare each word’s length, not the word itself, so the shortest word comes first.

It’s especially useful for sorting a list of more complex objects by one specific attribute:

python
people = [
    {"name": "Erin", "age": 29},
    {"name": "Jordan", "age": 24},
    {"name": "Maya", "age": 35},
]

print(sorted(people, key=lambda p: p["age"]))
# [{'name': 'Jordan', 'age': 24}, {'name': 'Erin', 'age': 29}, {'name': 'Maya', 'age': 35}]

Add reverse=True to either sorted() or .sort() to sort in descending order instead.

Dates and Times with datetime

The datetime module handles dates, times, and the arithmetic between them. A few of the basics:

python
import datetime

# a time: hour, minute, second
t = datetime.time(1, 25, 10)
print(t.hour)         # 1
print(t.microsecond)  # 0

print(datetime.time.min)  # 00:00:00

today = datetime.date.today()
print(today.year)   # e.g. 2026
print(today.month)  # e.g. 7
print(today.day)    # e.g. 20

datetime.date.today() always reflects whatever day the code actually runs on, so today.year, today.month, and today.day will differ depending on when you run this.

datetime has plenty more: formatting with strftime, parsing with strptime, arithmetic with timedelta, worth exploring further any time your program needs to work with real dates.

Try It

  1. Write a lambda that squares a number, and use it with map() over a list.
  2. Use filter() with a lambda to keep only the even numbers from a list.
  3. Build a list of dictionaries representing a few people (with at least a name and an age), and use sorted() with a key lambda to sort them by age.
  4. Get today’s date with datetime.date.today() and print just the month.

Recap

  • Lambdas are anonymous, single-expression functions, best for short, throwaway logic, especially alongside map, filter, and reduce.
  • Every lambda shares the same __name__, '<lambda>'; they’re not meant to be referenced by name later.
  • sorted() returns a new sorted list without mutating the original; .sort() mutates in place. Both accept key (what to sort by) and reverse=True (descending order).
  • datetime.time and datetime.date give you structured access to times and dates, including date.today() for the current date.

Next lesson: put generators, iterators, and decorators into practice with a set of exercises.