Avoid duplicated operations in lambda functions
<p>I'm using a lambda function to extract the number in a string:</p>

<pre><code>text = "some text with a number: 31"
get_number = lambda info,pattern: re.search('{}\s*(\d)'.format(pattern),info.lower()).group(1) if re.search('{}\s*(\d)'.format(pattern),info.lower()) else None
get_number(text,'number:')
</code></pre>

<p>How can I avoid to make this operation twice?:</p>

<pre><code>re.search('{}\s*(\d)'.format(pattern),info.lower()
</code></pre>

<p>You can use <code>findall()</code> instead, it handles a no match <em>gracefully</em>. <code>or</code> is the only statement needed to satisfy the return conditions. The <code>None</code> is evaluated last, thus returned if an empty list is found (<em>implicit truthiness of literals like lists</em>).</p>

<pre><code>&gt;&gt;&gt; get_number = lambda info,pattern: re.findall('{}\s*(\d)'.format(pattern),info.lower()) or None
&gt;&gt;&gt; print get_number(text, 'number:')
['3']
&gt;&gt;&gt; print get_number(text, 'Hello World!')
&gt;&gt;&gt;
</code></pre>

<p>That being said, I'd recommend defining a regular <strong>named</strong> function using <code>def</code> instead. You can extract more complex parts of this code to variables, leading to an easier to follow algorithm. Writing long anonymous function can lead to code smells. Something similar to below:</p>

<pre><code>def get_number(source_text, pattern):
    regex = '{}\s*(\d)'.format(pattern)
    matches = re.findall(regex, source_text.lower())
    return matches or None
</code></pre>

python regex lambda