-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlesson-17-lambda-functions.html
More file actions
107 lines (94 loc) · 9.96 KB
/
Copy pathlesson-17-lambda-functions.html
File metadata and controls
107 lines (94 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large">
<meta name="description" content="Python Lambda Functions — learn anonymous functions with lambda keyword. Master lambda syntax, use with sorted(), map(), filter(). Free interactive tutorial.">
<meta name="keywords" content="python lambda, anonymous function python, lambda function, python lambda example, python sorted key lambda">
<link rel="canonical" href="https://majedql29-spec.github.io/JometCode/lesson-17-lambda-functions.html">
<link rel="stylesheet" href="/design.css">
<meta property="og:title" content="Python Lambda Functions — Anonymous Functions | JometCode">
<meta property="og:description" content="Learn Python lambda functions — anonymous functions for sorted(), map(), filter(), and more.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://majedql29-spec.github.io/JometCode/lesson-17-lambda-functions.html">
<meta property="og:site_name" content="JometCode">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python Lambda Functions — Anonymous Functions | JometCode">
<meta name="twitter:description" content="Learn Python lambda functions — anonymous functions for sorted(), map(), filter().">
<title>Python Lambda Functions — Free Interactive Python Tutorial | JometCode</title>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://majedql29-spec.github.io/JometCode"},{"@type":"ListItem","position":2,"name":"Learn Python","item":"https://majedql29-spec.github.io/JometCode/learn.html"},{"@type":"ListItem","position":3,"name":"Lambda Functions","item":"https://majedql29-spec.github.io/JometCode/lesson-17-lambda-functions.html"}]}</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0b0b10; color: #e8e8ee; line-height: 1.7; }
.container { max-width: 800px; margin: 0 auto; padding: 32px 20px; }
h1 { font-size: 26px; margin-bottom: 4px; color: #f97316; font-family: ui-monospace, 'SF Mono', monospace; }
.meta { color: #5a5a6a; font-size: 13px; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 1px solid #22222e; display: flex; gap: 16px; }
.meta span { display: flex; align-items: center; gap: 4px; }
.meta .badge { display: inline-block; background: rgba(249,115,22,0.12); color: #f97316; font-size: 11px; padding: 1px 10px; border-radius: 10px; font-weight: 600; }
h2 { font-size: 18px; color: #e8e8ee; margin: 24px 0 10px; }
p { margin: 10px 0; color: #d1d5e0; font-size: 14px; }
code { background: #16161e; padding: 2px 6px; border-radius: 4px; font-family: ui-monospace, 'SF Mono', monospace; font-size: 13px; color: #f97316; }
pre { background: #16161e; border: 1px solid #22222e; border-radius: 8px; padding: 14px 16px; overflow-x: auto; margin: 12px 0; font-family: ui-monospace, 'SF Mono', monospace; font-size: 13px; color: #d1d5e0; line-height: 1.5; }
pre .kw { color: #c586c0; } pre .fn { color: #dcdcaa; } pre .str { color: #ce9178; } pre .cm { color: #6a9955; font-style: italic; } pre .num { color: #b5cea8; } pre .op { color: #d4d4d4; } pre .va { color: #9cdcfe; }
ul { margin: 8px 0 8px 20px; color: #d1d5e0; font-size: 14px; }
li { margin: 4px 0; }
.tip { background: rgba(249,115,22,0.06); border-left: 3px solid #f97316; padding: 12px 16px; border-radius: 0 6px 6px 0; margin: 16px 0; font-size: 13px; color: #d1d5e0; }
.nav-links { display: flex; justify-content: space-between; margin-top: 32px; padding-top: 16px; border-top: 1px solid #22222e; }
.nav-links a { color: #f97316; text-decoration: none; font-size: 14px; }
.nav-links a:hover { text-decoration: underline; }
.nav-links .next { text-align: right; }
.cta { text-align: center; margin: 32px 0; padding: 20px; background: #121216; border: 1px solid #22222e; border-radius: 10px; }
.cta a { display: inline-block; background: #f97316; color: #fff; padding: 10px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; }
.cta a:hover { background: #ea580c; }
.back-link { display: inline-flex; align-items: center; gap: 6px; color: #5a5a6a; font-size: 13px; text-decoration: none; margin-bottom: 20px; }
.back-link:hover { color: #f97316; }
</style>
<script defer src="https://cloud.umami.is/script.js" data-website-id="e580f92e-6fd0-405b-bce3-f8d667558732"></script>
</head>
<body>
<div class="container">
<a href="/learn.html" class="back-link">← Back to Course</a>
<h1>Lesson 17: Lambda Functions</h1>
<div class="meta"><span class="badge">Intermediate</span><span>⏰ 7 min</span></div>
<p>A <strong>lambda</strong> is a small, anonymous function defined with the <code>lambda</code> keyword. Unlike regular functions defined with <code>def</code>, lambdas are written in a single expression, have no name, and cannot contain statements or annotations. Syntax: <code>lambda arguments: expression</code>. The expression is evaluated and returned automatically — no <code>return</code> keyword needed: <code>lambda x, y: x + y</code> creates a function that adds two numbers.</p>
<pre><span class="cm"># Lambda = anonymous function</span>
square = <span class="kw">lambda</span> <span class="va">x</span>: x <span class="op">**</span> <span class="num">2</span>
<span class="kw">print</span>(square(<span class="num">5</span>))
add = <span class="kw">lambda</span> <span class="va">a</span>, <span class="va">b</span>: a <span class="op">+</span> b
<span class="kw">print</span>(add(<span class="num">3</span>, <span class="num">7</span>))
<span class="cm"># Use with sorted</span>
points = [(<span class="num">1</span>, <span class="num">5</span>), (<span class="num">3</span>, <span class="num">2</span>), (<span class="num">2</span>, <span class="num">8</span>)]
points.<span class="fn">sort</span>(key=<span class="kw">lambda</span> <span class="va">p</span>: p[<span class="num">1</span>])
<span class="kw">print</span>(<span class="str">"Sorted by y:"</span>, points)</pre>
<p>Lambdas shine when you need a simple, throwaway function, especially as an argument to higher-order functions:</p>
<ul>
<li><strong>sorted() with a custom key:</strong> <code>students.sort(key=lambda s: s["grade"])</code> — sort a list of dicts by the "grade" field. Also works with <code>max()</code> and <code>min()</code>: <code>max(points, key=lambda p: p[1])</code> finds the tuple with the largest y-coordinate.</li>
<li><strong>map():</strong> <code>list(map(lambda x: x * 1.15, prices))</code> — apply a 15% tax to each price.</li>
<li><strong>filter():</strong> <code>list(filter(lambda x: len(x) > 5, words))</code> — keep only words longer than 5 characters.</li>
</ul>
<h2>When NOT to use lambda:</h2>
<p>If the logic requires statements (if/elif/else chains, loops, try/except, variable assignments), you cannot use lambda — use <code>def</code>. If the function is used in multiple places, define it once with <code>def</code> to avoid repetition. If the lambda expression is too long to read comfortably on one line, use <code>def</code>. As a rule of thumb: if you need more than a single expression or the expression is longer than ~80 characters, write a regular function.</p>
<h2>Lambda vs def comparison:</h2>
<p>Both create function objects that can be called the same way. <code>def</code> functions have a name (helpful in tracebacks), support docstrings, annotations, and multiple statements. Lambdas are limited to a single expression and have no name or docstring — if they raise an error, the traceback shows <code><lambda></code> which is less helpful for debugging. Performance-wise, they are identical — choice is purely about readability and capability.</p>
<h2>Common mistakes:</h2>
<p>Trying to use statements inside a lambda — <code>lambda x: return x + 1</code> is a <code>SyntaxError</code>. Using a lambda when <code>functools.partial</code> or a regular function would be clearer. Assigning a lambda to a variable (<code>add = lambda x, y: x + y</code>) is poor style — if you're going to name it, use <code>def</code> instead. That's what <code>def</code> is for.</p>
<h2>Best practices:</h2>
<p>Use lambdas only for simple, single-use operations. Prefer list comprehensions over <code>map()</code> with lambdas for readability. Use <code>key=</code> arguments in <code>sorted()</code>, <code>max()</code>, <code>min()</code> — these are the most common and idiomatic use cases. If the lambda body is complex, refactor it into a named function with a descriptive name.</p>
<h2>Real-world use case:</h2>
<p>Sorting a list of product objects by price descending: <code>products.sort(key=lambda p: p["price"], reverse=True)</code>. Finding the employee with the highest salary: <code>best = max(employees, key=lambda e: e.salary)</code>. Grouping data with <code>itertools.groupby</code>: <code>for city, group in groupby(people, key=lambda p: p["city"]):</code>.</p>
<div class="tip"><strong>Try it:</strong> Use <code>max()</code> with a lambda to find the longest word in a list: <code>words = ["cat", "elephant", "dog"]; print(max(words, key=lambda w: len(w)))</code>. Then use <code>sorted()</code> with a lambda that sorts by the last character of each word. Finally, compare the readability of a lambda vs a <code>def</code> for a multi-step key function.</div>
<div class="cta">
<a href="/learn.html#lesson-16">Open Interactive Lesson →</a>
<p>Run this code directly in your browser with our free Python IDE.</p>
</div>
<div class="nav-links">
<a href="/lesson-16-file-handling.html">← Lesson 16: File Handling</a>
<a href="/lesson-18-working-with-json.html" class="next">Lesson 18: Working with JSON →</a>
</div>
<div style="text-align:center;font-size:12px;color:#5a5a6a;margin-top:32px;">
© 2026 JometCode | <a href="/cheatsheet.html" style="color:#5a5a6a;">Python Cheatsheet</a>
</div>
</div>
</body>
</html>