Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Are you talking about <a href="https://docs.python.org/3.5/tutorial/controlflow.html#lambda-expressions" rel="noreferrer">lambda functions</a>? Like</p> <pre><code>lambda x: x**2 + 2*x - 5 </code></pre> <p>Those things are actually quite useful. Python supports a style of programming called <em>functional programming</em> where you can pass functions to other functions to do stuff. Example:</p> <pre><code>mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <p>sets <code>mult3</code> to <code>[3, 6, 9]</code>, those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than</p> <pre><code>def filterfunc(x): return x % 3 == 0 mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <p>Of course, in this particular case, you could do the same thing as a list comprehension:</p> <pre><code>mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0] </code></pre> <p>(or even as <code>range(3,10,3)</code>), but there are many other, more sophisticated use cases where you can't use a list comprehension and a lambda function may be the shortest way to write something out.</p> <ul> <li><p>Returning a function from another function</p> <pre><code>&gt;&gt;&gt; def transform(n): ... return lambda x: x + n ... &gt;&gt;&gt; f = transform(3) &gt;&gt;&gt; f(4) 7 </code></pre> <p>This is often used to create function wrappers, such as Python's decorators.</p></li> <li><p>Combining elements of an iterable sequence with <code>reduce()</code></p> <pre><code>&gt;&gt;&gt; reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9]) '1, 2, 3, 4, 5, 6, 7, 8, 9' </code></pre></li> <li><p>Sorting by an alternate key</p> <pre><code>&gt;&gt;&gt; sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x)) [5, 4, 6, 3, 7, 2, 8, 1, 9] </code></pre></li> </ul> <p>I use lambda functions on a regular basis. It took me a while to get used to them, but eventually I came to understand that they're a very valuable part of the language.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload