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 akeyfunction - Manipulate dates and times using the
datetimemodule
💡 Why this matters: Lambdas are the concise, throwaway functions you’ll pass to things like
sorted(),map(), andfilter()all the time.datetimeis 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:
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:
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:
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):
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:
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:
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:
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:
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
- Write a lambda that squares a number, and use it with
map()over a list. - Use
filter()with a lambda to keep only the even numbers from a list. - Build a list of dictionaries representing a few people (with at least a
nameand anage), and usesorted()with akeylambda to sort them by age. - 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, andreduce. - 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 acceptkey(what to sort by) andreverse=True(descending order).datetime.timeanddatetime.dategive you structured access to times and dates, includingdate.today()for the current date.
Next lesson: put generators, iterators, and decorators into practice with a set of exercises.