title: if else for None in Python
body: <p>Any way to write this in one line in Python, or even better, as an expression instead of a statement?</p>
  
  <pre><code>parts = ['0', '1', 'None', '5', '4']
  [int(p) for p in parts]
  </code></pre>
  
  <p>This of course gives an error,</p>
  
  <pre><code>ValueError: invalid literal for int() with base 10: 'None'
  </code></pre>
  
  <p>So:</p>
  
  <pre><code>[p=='None' and None or int(p) for p in parts]
  </code></pre>
  
  <p>Doesn't work because you can't use <code>None</code> with the and/or construct reliably.  (Even if <code>p=='None'</code> is true, <code>None</code> is equivalent to false so it goes to the <code>or</code> part.)</p>
  
  <pre><code>[int(p) if p=='None' else None for p in parts]
  </code></pre>
  
  <p>Also doesn't work.  I guess it evaluates <code>int(p)</code> before the conditions?  (Seems odd semantics.)</p>
  
  <pre><code>a = []
  for p in parts:
      if p=='None': k = None; else: k = int(p)
      a.append(k)
  </code></pre>
  
  <p>Nope, invalid syntax.</p>
  
  <pre><code>a = []
  for p in parts:
      if p=='None':
          k = None;
      else:
          k = int(p)
      a.append(k)
  </code></pre>
  
  <p>Ah! Finally.  But isn't there a shorter way to write such a simple loop?</p>