Pythonのラムダ(lambda)式関数とはなにか?sorted や map と一緒に使う方法

Python の lambda 式は次のように使います。

add = lambda x, y: x + y

print(add(3, 5))
# 8

これだけだと「通常の関数定義とどう違うの?」と思いますね。下のコードを見ると、だんだんラムダ式の利便性がわかってきます。

cities = ["London", "Tokyo", "New York", "Oslo", "Berlin"]

sorted_cities = sorted(cities, key=lambda city: len(city))

print(sorted_cities)
# ['Oslo', 'Tokyo', 'London', 'Berlin', 'New York']

文字列の長さを返す関数をラムダ式としてつくったものの、名前はありません。上のような関数を無名関数といいます。ラムダ式は sorted の条件として使われています。

ラムダ式は map とも相性がいい。

nums = [1, 2, 3, 4]

doubled = list(map(lambda x: x * 2, nums))

print(doubled)
# [2, 4, 6, 8]

map は、リストなどの各要素に、同じ関数を適用して新しいリスト(的なもの)をつくります。

リストからリストをつくる、とイメージしてもいいです。ただし、できあがるものはリストそのものではありません。

nums = [1, 2, 3, 4]

result = map(lambda x: x * 2, nums)
doubled = list(result)

print(result)
# <map object at 0x102415840>

print(type(result))
# <class 'map'>

print(doubled)
# [2, 4, 6, 8]

map は map オブジェクトを返し、要素を具体的に抽出するにはリストへキャストします。