breaking a complex string ('2,3-5,50-60,70') into list inplace
<p>complexstring: '2,3-5,50-52,70'</p>

<p>output required: [2,3,4,5,50,51,52,70]</p>

<p>Here is what I attempted and succeeded</p>

<pre><code>a = '2,3-5,50-52,70'
data = []
[data.extend(range(int(r.split('-')[0]),int(r.split('-')[1])+1)) if r.find('-') != -1 else data.append(int(r)) for r in a.split(',')]
print data
</code></pre>

<blockquote>
  <p>output achieved: [2, 3, 4, 5, 50, 51, 52, 70]</p>
</blockquote>

<p>But my question is there a way to do in place with in list comprehension? What I exactly mean is </p>

<p><code>data = [#perform some processing on a here to get directly output]</code></p>

<p>instead of pre-declaring list <code>data</code> and keep appending or extending it.</p>

<p>P.S: I want to achieve it with just list comprehension without defining additional function.</p>

<p>I doubt it's possible to do it with a single list comprehension. You could abuse <code>sum()</code> and do other horrible things in one line, though:</p>

<pre><code>sum([range(*(2 * map(int, c.split('-')))[:2]) + [int(c.split('-')[-1])] for c in text.split(',')], [])
</code></pre>

<p>A cleaner way would be to use a generator:</p>

<pre><code>def parse_sequence(text):
    for chunk in text.split(','):
        parts = map(int, chunk.split('-'))

        if len(parts) == 1:
            yield parts[0]
        else:
            for n in xrange(parts[0], parts[1] + 1):
                yield n
</code></pre>

<p>Please don't do it in one line. The second approach is twice as fast and isn't written to be hard to read. There's no reason to use the first one.</p>

python python-2.7 list-comprehension