How can I generate a list and flatten it the same time in python?
<p>This is more of a refactoring question, as the code works as is. But since I am still learning <code>Python</code>, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.</p>

<p>So I have the following statement:</p>

<p><code>numbers = [re.split(' ?- ?', ticket.text.strip()) for ticket in tickets]</code></p>

<p>which obviously generates a list of lists. However, I want to have just a single list of the numbers taken out from that regex.</p>

<p>So this is the second line of code that flattens the above list (I found this solution here, on <code>StackOverflow</code> btw):</p>

<p><code>flat = [item for setlist in numbers for item in setlist]</code></p>

<p>Main thing I am trying to achieve is to have this on 1 single line. Otherwise, I could of course have a normal <code>for .. in</code> loop, that would append each number to numbers list, but I like keeping it on 1 line. </p>

<p>If this is the best it can get, I would also love to know that please.. :)</p>

<p>You can achieve it using <code>chain</code> and <code>map</code> in single line as:</p>

<pre><code>list(chain(*map(lambda x: re.split(' ?- ?', x.text.strip()), tickets)))
</code></pre>

<p><strong>Suggestion:</strong></p>

<p>There is no need to use <code>regex</code> here, because you may achieve the same using <code>split</code> function of Python. Hence, your answer will become:</p>

<pre><code>list(chain(*map(lambda x: x.text.replace(' ', '').split('-')), tickets)))
</code></pre>

<p><strong>Explaination:</strong></p>

<p><code>chain</code> function from the <a href="https://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools</code></a> library is used to umwrap the list. Below is the sample example</p>

<pre><code>&gt;&gt;&gt; from itertools import chain
&gt;&gt;&gt; my_nested_list = [[1,2,3], [4,5,6]]
&gt;&gt;&gt; list(chain(*my_nested_list))
[1, 2, 3, 4, 5, 6]
</code></pre>

<p>Whereas <code>map</code> function is used to call the passed <code>function</code> (in this case <code>lambda</code> function) on each item of <code>list</code>.</p>

<pre><code>&gt;&gt;&gt; my_nested_list = [[1,2,3], [4,5,6]]
&gt;&gt;&gt; map(lambda x: x[0], my_nested_list)
[1, 4]
</code></pre>

<p>And, <code>split</code> is used to split the content of string based on substring. For example:</p>

<pre><code>&gt;&gt;&gt; x = 'hey you - i am here'
&gt;&gt;&gt; x.split('-')
['hey you ', ' i am here']  # Same answer as your regex
</code></pre>

python