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>Oneliner:</p>

<pre><code>a = '2,3-5,50-52,70'
data = sum([[int(x)] if x.isdigit() else list(range(int(x.split('-')[0]),1+int(x.split('-')[1]))) for x in a.split(",")],[])
print(data)
</code></pre>

<p>variant without <code>isdigit</code>:</p>

<pre><code>data = sum([list(range(int(x.split('-')[0]),1+int(x.split('-')[1]))) if "-" in x else [int(x)] for x in a.split(",")],[])
</code></pre>

<p>(I use sum with a start value of <code>[]</code> which allows to "flatten" the created lists of one level)</p>

<p>result:</p>

<pre><code>[2, 3, 4, 5, 50, 51, 52, 70]
</code></pre>

<p>That said, that's just for fun:</p>

<ul>
<li>I don't know if the performance is good, though, since there are a lot of list creations and split calls that could be avoided (actually I think it's bad)</li>
<li>It's rather easy to build, but hard to maintain/understand</li>
</ul>

python python-2.7 list-comprehension