title: Nested List Comprehension with if/else
body: <p>I have a function that takes a string in a format such as '1,3-5,7,19' and will output the list <code>[1, 3, 4, 5, 7, 19]</code>.</p>
  
  <p>However, I was thinking that maybe this was simple enough to do with a nested list comprehension.</p>
  
  <p>My original function is:</p>
  
  <pre><code>result = []
  for x in row_range.split(','):
      if '-' in x:
          for y in range(int(x.split('-')[0]), int(x.split('-')[1]) + 1)):
              result.append(y)
      else:
          result.append(int(x))
  </code></pre>
  
  <p>I thought the comprehension would be something like:</p>
  
  <pre><code>result = [y for x in row_range.split(',') if '-' in x else int(x) for y in range(int(x.split('-')[0]), int(x.split('-')[1] + 1)]
  </code></pre>
  
  <p>or even</p>
  
  <pre><code>result = [y for x in row_range.split(',') if '-' in x for y in range(int(x.split('-')[0]), int(x.split('-')[1] + 1) else int(x)]
  </code></pre>
  
  <p>but these are SyntaxError. Moving the if/else to the front of the comprehension as </p>
  
  <pre><code>result = [y if '-' in x else int(x) for x in row_range.split(',') for y in range(int(x.split('-')[0]), int(x.split('-')[1]) + 1)]
  </code></pre>
  
  <p>results in an IndexError: list index out of range.</p>
  
  <p>Is this possible? I already have a function that handles it nicely and is more readable but I am simply curious if this can be accomplished in python.</p>