[{"data":1,"prerenderedAt":66},["ShallowReactive",2],{"qa-\u002Fpython\u002Ffunctions\u002Flambdas":3},{"page":4,"siblings":53,"blog":44},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":44,"seo":45,"seoDescription":46,"stem":47,"subtopic":48,"topic":49,"topicSlug":50,"updated":51,"__hash__":52},"qa\u002Fpython\u002Ffunctions\u002Flambdas.md","Lambdas",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,4,"\u002Fpython\u002Ffunctions\u002Flambdas",[23,28,32,36,40],{"id":24,"difficulty":25,"q":26,"a":27},"lambda-syntax","easy","What is a lambda and what are its limitations?","A **lambda** is an anonymous, single-**expression** function:\n`lambda args: expression`. It returns the expression's value automatically\n(no `return`). Its limitation is exactly that — it can hold only **one\nexpression**, no statements, assignments, loops, or annotations.\n\n```python\nsquare = lambda x: x * x\nsquare(5)                  # 25\n\nadd = lambda a, b=1: a + b # defaults allowed\nadd(10)                    # 11\n\n# NOT allowed: lambda x: (y = x; return y)  — no statements\n```\n\nBecause it's an expression, a lambda can be passed inline wherever a\nfunction is expected. Keep them short; anything needing multiple lines or a\ndocstring should be a named `def`.\n",{"id":29,"difficulty":14,"q":30,"a":31},"lambda-vs-def","When should you use a lambda versus a def?","Use a **lambda** for a tiny throwaway function passed **inline** as an\nargument (a sort key, a callback). Use **`def`** for anything reused, named,\ndocumented, or non-trivial. A named function gives a useful `__name__` in\ntracebacks; a lambda just shows `\u003Clambda>`.\n\n```python\n# good lambda: inline, one-off\nsorted(words, key=lambda w: len(w))\n\n# prefer def: reused \u002F needs a name\ndef by_length(w):\n    return len(w)\n```\n\nPEP 8 even discourages **assigning** a lambda to a name\n(`f = lambda x: ...`) — if you need a name, just use `def`. Lambdas shine as\narguments, not as definitions.\n",{"id":33,"difficulty":14,"q":34,"a":35},"higher-order-functions","What is a higher-order function?","A **higher-order function** is one that **takes a function as an argument\nand\u002For returns a function**. They enable composing and parameterizing\nbehavior. Built-in examples include `map`, `filter`, `sorted`, and the\n`functools` tools.\n\n```python\ndef apply_twice(fn, x):\n    return fn(fn(x))           # takes a function\n\napply_twice(lambda n: n + 3, 10)   # 16\n\nlist(map(str.upper, [\"a\", \"b\"]))   # ['A', 'B']\nlist(filter(lambda n: n > 0, [-1, 2, -3, 4]))  # [2, 4]\n```\n\nHigher-order functions are the foundation of functional-style Python and of\ndecorators (which both take and return functions). They let you pass\n*behavior* around as data.\n",{"id":37,"difficulty":14,"q":38,"a":39},"key-argument","How does the key argument work in sorted, max, and min?","`key` takes a **function** applied to each element to derive the value used\nfor **comparison** — the elements themselves aren't changed, only how\nthey're ranked. It's used by `sorted`, `list.sort`, `max`, and `min`.\n\n```python\nwords = [\"banana\", \"kiwi\", \"apple\"]\n\nsorted(words, key=len)                 # ['kiwi', 'apple', 'banana']\nmax(words, key=len)                    # 'banana'\nsorted(words, key=str.lower)           # case-insensitive\n\npeople = [(\"ada\", 36), (\"grace\", 45)]\nmax(people, key=lambda p: p[1])        # ('grace', 45)\n```\n\n`key` is called **once per element** (efficient), unlike the old `cmp`\nstyle. For multi-level sorts, return a **tuple**:\n`key=lambda p: (p.last, p.first)`.\n",{"id":41,"difficulty":14,"q":42,"a":43},"first-class-functions","What does it mean that functions are first-class objects?","In Python, functions are **first-class objects**: they can be assigned to\nvariables, stored in data structures, passed as arguments, and **returned**\nfrom other functions — just like any value. This is what makes higher-order\nfunctions and closures possible.\n\n```python\ndef shout(s): return s.upper() + \"!\"\n\nf = shout                 # assign to a variable\nf(\"hi\")                   # 'HI!'\n\ndispatch = {\"loud\": shout}        # store in a dict\ndispatch[\"loud\"](\"hey\")           # 'HEY!'\n\ndef make_op(op):                  # return a function\n    return (lambda a, b: a + b) if op == \"+\" else (lambda a, b: a - b)\nmake_op(\"+\")(2, 3)                # 5\n```\n\nTreating functions as values enables strategy\u002Fdispatch tables, callbacks,\nand decorators. There's no separate \"function pointer\" concept — the\nfunction *is* the object.\n",null,{"description":11},"Python interview questions on lambda syntax and limitations, lambda vs def, higher-order functions, the key argument in sorted\u002Fmax\u002Fmin, and functions as first-class objects.","python\u002Ffunctions\u002Flambdas","Lambdas & Higher-Order Functions","Functions","functions","2026-06-18","9_y3LjVbDK5c4cIpcmC5IQFqaQxIZJqZxiPop420_2E",[54,58,61,65],{"subtopic":55,"path":56,"order":57},"Decorators","\u002Fpython\u002Ffunctions\u002Fdecorators",1,{"subtopic":59,"path":60,"order":12},"Function Arguments","\u002Fpython\u002Ffunctions\u002Farguments",{"subtopic":62,"path":63,"order":64},"Closures & Scope","\u002Fpython\u002Ffunctions\u002Fclosures",3,{"subtopic":48,"path":21,"order":20},1781808680017]