{"id":429,"date":"2026-04-18T19:08:17","date_gmt":"2026-04-18T19:08:17","guid":{"rendered":"http:\/\/askpython.com\/?p=429"},"modified":"2026-04-18T19:12:50","modified_gmt":"2026-04-18T19:12:50","slug":"python-lambda-anonymous-function","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/python-lambda-anonymous-function","title":{"rendered":"Python Lambda Anonymous Function"},"content":{"rendered":"\n<p>A lambda function is an anonymous function defined with the <code>lambda<\/code> keyword. It can take any number of arguments but can only contain a single expression. The result of that expression is returned automatically.<\/p>\n\n\n\n<p>The syntax is <code>lambda arguments: expression<\/code>. There is no <code>return<\/code> statement because the expression is evaluated and its result is returned implicitly. This makes lambdas useful for short throwaway functions where defining a full <code>def<\/code> would be overkill.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Lambda Syntax Explained<\/h2>\n\n\n\n<p>Compare a regular function with its lambda equivalent. Both do the same thing.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Regular function\ndef square(x):\n    return x ** 2\n\n# Lambda equivalent\nsquare = lambda x: x ** 2\n\nprint(square(5))  # 25\n<\/pre><\/div>\n\n\n<p>Lambda arguments work exactly like def arguments. You can have positional args, keyword args, defaults, and *args.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# No arguments\nnoop = lambda: 42\nprint(noop())  # 42\n\n# Multiple arguments\nadd = lambda x, y: x + y\nprint(add(3, 4))  # 7\n\n# With default argument\npower = lambda x, exp=2: x ** exp\nprint(power(3))   # 9\nprint(power(3, 3)) # 27\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Using Lambdas with Built-in Functions<\/h2>\n\n\n\n<p>Lambda functions shine when combined with Python built-ins like <code>map<\/code>, <code>filter<\/code>, and <code>sorted<\/code>. These functions accept a callable as their first argument, and lambdas provide that callable without the overhead of a named function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">map() with Lambda<\/h3>\n\n\n\n<p><code>map(function, iterable)<\/code> applies the function to every item in the iterable and returns an iterator.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#x5B;1, 2, 3, 4, 5]\n\nsquares = list(map(lambda x: x ** 2, numbers))\nprint(squares)  # &#x5B;1, 4, 9, 16, 25]\n\nnames = &#x5B;&#039;alice&#039;, &#039;bob&#039;, &#039;charlie&#039;]\nupper = list(map(lambda s: s.upper(), names))\nprint(upper)  # &#x5B;&#039;ALICE&#039;, &#039;BOB&#039;, &#039;CHARLIE&#039;]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">filter() with Lambda<\/h3>\n\n\n\n<p><code>filter(function, iterable)<\/code> keeps only the items where the function returns True.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#x5B;1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nevens = list(filter(lambda x: x % 2 == 0, numbers))\nprint(evens)  # &#x5B;2, 4, 6, 8, 10]\n\nwords = &#x5B;&#039;hi&#039;, &#039;hello&#039;, &#039;hey&#039;, &#039;yo&#039;, &#039;greetings&#039;]\nlong_words = list(filter(lambda w: len(w) &gt; 3, words))\nprint(long_words)  # &#x5B;&#039;hello&#039;, &#039;greetings&#039;]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">sorted() with Lambda<\/h3>\n\n\n\n<p>The <code>key<\/code> argument of <code>sorted<\/code> accepts a function. Lambda is perfect here because you rarely need a named function for sorting logic.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npeople = &#x5B;\n    {&#039;name&#039;: &#039;Alice&#039;, &#039;age&#039;: 30},\n    {&#039;name&#039;: &#039;Bob&#039;, &#039;age&#039;: 25},\n    {&#039;name&#039;: &#039;Charlie&#039;, &#039;age&#039;: 35}\n]\n\n# Sort by age\nby_age = sorted(people, key=lambda p: p&#x5B;&#039;age&#039;])\nprint(&#x5B;p&#x5B;&#039;name&#039;] for p in by_age])  # &#x5B;&#039;Bob&#039;, &#039;Alice&#039;, &#039;Charlie&#039;]\n\n# Sort by name length\nby_name_len = sorted(people, key=lambda p: len(p&#x5B;&#039;name&#039;]))\nprint(&#x5B;p&#x5B;&#039;name&#039;] for p in by_name_len])  # &#x5B;&#039;Bob&#039;, &#039;Alice&#039;, &#039;Charlie&#039;]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">max() and min() with Lambda<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\norders = &#x5B;\n    {&#039;product&#039;: &#039;Laptop&#039;, &#039;price&#039;: 999},\n    {&#039;product&#039;: &#039;Mouse&#039;, &#039;price&#039;: 29},\n    {&#039;product&#039;: &#039;Keyboard&#039;, &#039;price&#039;: 79}\n]\n\nmost_expensive = max(orders, key=lambda o: o&#x5B;&#039;price&#039;])\ncheapest = min(orders, key=lambda o: o&#x5B;&#039;price&#039;])\nprint(most_expensive&#x5B;&#039;product&#039;])  # Laptop\nprint(cheapest&#x5B;&#039;product&#039;])        # Mouse\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Lambda vs list comprehension<\/h2>\n\n\n\n<p>Everything you can do with <code>map<\/code> and <code>filter<\/code> combined with lambda, you can do with a list comprehension. List comprehensions are generally preferred in Python for readability.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#x5B;1, 2, 3, 4, 5]\n\n# Lambda + map - don&#039;t do this\nsquares = &#x5B;x ** 2 for x in numbers]  # List comprehension is cleaner\n\n# Lambda + filter - don&#039;t do this\nevens = &#x5B;x for x in numbers if x % 2 == 0]  # List comprehension is cleaner\n\n# Where lambda IS appropriate with sorted, max, min\nmax_val = max(numbers, key=lambda x: -x)  # Finds maximum\n<\/pre><\/div>\n\n\n<p>The exception is <code>sorted<\/code>, <code>max<\/code>, and <code>min<\/code> with a key function. You cannot replace these with list comprehensions, so lambda is genuinely useful there.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Lambda and Closures<\/h2>\n\n\n\n<p>Lambda captures variables from its enclosing scope at definition time, not at call time. This is called closure.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef make_multiplier(factor):\n    return lambda x: x * factor\n\ndouble = make_multiplier(2)\ntriple = make_multiplier(3)\n\nprint(double(5))   # 10\nprint(triple(5))   # 15\n\n# The lambda captured the `factor` argument at definition time\n# Each lambda has its own closure value\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with Lambda<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mutable default arguments<\/h3>\n\n\n\n<p>Never use a lambda to create a function that modifies a default mutable argument. This is a common trap that leads to subtle bugs.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# WRONG - this is a classic Python gotcha\nbad_func = lambda lst=&#x5B;]: lst.append(&#039;x&#039;)\n\n# Default mutable arguments are shared across calls\n# Use a proper function with default None instead\ndef good_func(lst=None):\n    if lst is None:\n        lst = &#x5B;]\n    lst.append(&#039;x&#039;)\n    return lst\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Multi-expression lambdas<\/h3>\n\n\n\n<p>If your lambda is getting complex, it is a sign you should use a regular <code>def<\/code> function. Lambdas are meant for single expressions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;pre class=&quot;wp-block-syntaxhighlighter-code&quot;&gt;# WRONG - lambda too complex\ncomplex_lambda = lambda x: (x &gt; 0 and &#039;positive&#039; or x &lt; 0 and &#039;negative&#039; or &#039;zero&#039;)\n# CORRECT - use def\ndef classify(x):\n    if x &gt; 0: return &#039;positive&#039;\n    elif x &lt; 0: return &#039;negative&#039;\n    return &#039;zero&#039;&lt;\/pre&gt;\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">When to Use Lambda vs def<\/h2>\n\n\n\n<p>Use lambda when you need a short, throwaway function for <code>sorted<\/code>, <code>max<\/code>, <code>min<\/code>, <code>map<\/code>, or <code>filter<\/code>. Use <code>def<\/code> when the function needs multiple statements, documentation, or is used in multiple places.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use lambda with <code>sorted(key=...)<\/code> &#8211; genuinely the best tool<\/li>\n\n\n\n<li>Use lambda with <code>max\/min(key=...)<\/code> &#8211; genuinely the best tool<\/li>\n\n\n\n<li>Use lambda with <code>map\/filter<\/code> &#8211; list comprehensions are usually better<\/li>\n\n\n\n<li>Use def for anything over 2-3 lines of code<\/li>\n\n\n\n<li>Use def if the function is referenced in multiple places<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practical Example: Sorting a Table<\/h2>\n\n\n\n<p>Lambdas are most practical when sorting data structures. Here is a realistic example sorting a list of records by multiple fields.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nemployees = &#x5B;\n    {&#039;name&#039;: &#039;Alice&#039;, &#039;dept&#039;: &#039;Engineering&#039;, &#039;salary&#039;: 90000},\n    {&#039;name&#039;: &#039;Bob&#039;, &#039;dept&#039;: &#039;Sales&#039;, &#039;salary&#039;: 75000},\n    {&#039;name&#039;: &#039;Charlie&#039;, &#039;dept&#039;: &#039;Engineering&#039;, &#039;salary&#039;: 95000},\n    {&#039;name&#039;: &#039;Diana&#039;, &#039;dept&#039;: &#039;Sales&#039;, &#039;salary&#039;: 80000}\n]\n\n# Sort by dept, then by salary descending within each dept\nsorted_employees = sorted(\n    employees,\n    key=lambda e: (e&#x5B;&#039;dept&#039;], -e&#x5B;&#039;salary&#039;])\n)\n\nfor emp in sorted_employees:\n    print(f&quot;{emp&#x5B;&#039;dept&#039;]:12} {emp&#x5B;&#039;salary&#039;]:8} {emp&#x5B;&#039;name&#039;]}&quot;)\n# Engineering   95000 Charlie\n# Engineering   90000 Alice\n# Sales         80000 Diana\n# Sales         75000 Bob\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">FAQ<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Can a lambda function have multiple statements?<\/strong> No. A lambda can only contain a single expression. Use a regular <code>def<\/code> function for multiple statements.<\/li>\n\n\n\n<li><strong>Can lambdas access variables outside themselves?<\/strong> Yes. Lambdas support closures and can access variables from the enclosing scope.<\/li>\n\n\n\n<li><strong>What is the difference between <code>def<\/code> and lambda?<\/strong> Lambda defines an anonymous expression and returns its result automatically. <code>def<\/code> defines a named function that can contain multiple statements.<\/li>\n\n\n\n<li><strong>When should I prefer list comprehension over map\/filter with lambda?<\/strong> Almost always. List comprehensions are more readable in Python. The exception is <code>sorted(key=...)<\/code> and <code>max\/min(key=...)<\/code>.<\/li>\n\n\n\n<li><strong>Can I use lambda without any arguments?<\/strong> Yes. <code>lambda: 42<\/code> creates a function that takes no arguments and returns 42.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>A lambda function is an anonymous function defined with the lambda keyword. It can take any number of arguments but can only contain a single expression. The result of that expression is returned automatically. The syntax is lambda arguments: expression. There is no return statement because the expression is evaluated and its result is returned [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":66051,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-429","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/429","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=429"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/429\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/66051"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=429"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=429"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=429"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}