0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】lambda式(無名関数)の書き方と使い方まとめ

Last updated at Posted at 2025-04-29

Pythonには、関数を「名前なしでその場で定義する」ことができる lambda という機能があります。
本記事では、lambda式の基本的な使い方から、map()filter()sorted() との実用的な組み合わせまでをわかりやすくまとめます。

lambda式とは?

関数を通常の def ではなく、名前をつけずに1行で定義できる構文です。
lambda は「無名関数」とも呼ばれ、ちょっとした処理をその場で書きたいときに使われます。

lambda式の書き方

lambda 引数: 戻り値

例:

lambda x: x + 1

これは「xを受け取り、xに1を足して返す関数」です。

通常の関数とlambda式の違い

# 通常の関数
def add(x, y):
    return x + y

# 無名関数(lambda)
lambda x, y: x + y

処理内容は同じですが、lambda式は名前をつけずにその場で定義できる点が異なります。

lambda式の基本例

数値を2倍にする関数

double = lambda x: x * 2
print(double(4))  # → 8

文字列の長さを返す関数

get_len = lambda s: len(s)
print(get_len("python"))  # → 6

lambda式 × 組み込み関数の実用例

map関数と組み合わせてリストの要素を2倍にする

nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)  # → [2, 4, 6, 8]

filter関数と組み合わせて偶数だけ取り出す

nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)  # → [2, 4, 6]

sorted関数と組み合わせて名前順に並び替える

data = [(1, 'Noro'), (2, 'Nakao'), (3, 'Miyaoka'), (4, 'Kimura')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
# → [(4, 'Kimura'), (3, 'Miyaoka'), (2, 'Nakao'), (1, 'Noro')]

注意点

  • lambda式は1行でしか書けません(複雑な処理はできません)
  • 条件分岐やループなどを含む場合は、通常の def を使う方が可読性が高いです
  • あくまで一時的に使いたい簡単な関数に向いています

おまけ:リスト内包表記との違い

以下の2つは、ほぼ同じ結果になります。

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

# リスト内包表記
doubled = [x * 2 for x in nums]

リスト内包表記の方がPythonらしく読みやすいですが、
lambdamapfilter のような関数的な書き方と相性が良いです。

おわりに

lambda は最初はとっつきにくいですが、短く関数を書く手段として非常に便利だと感じました。
特に sorted(), map(), filter() との組み合わせは、Python3エンジニア認定基礎試験でも頻出ですので、この機会にしっかり押さえます!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?