if-else in python list comprehensions
<p>is it possible to write list comprehensions for the following python code:</p>

<pre><code>for str in range(0,len(mixed_content)):
    if (mixed_content[str].isdigit()):
        num_list.append(mixed_content[str])
    else:
        string_list.append(mixed_content[str])
</code></pre>

<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>

<pre><code>num_list , string_list = [   mixed_content[str]  for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>

<p>It's not possible as-is, but if you're looking for one-liners you can do that with a ternary expression inside your loop (saves a test and is compact):</p>

<pre><code>num_list=[]
string_list=[]
for s in ["45","hello","56","foo"]:
    (num_list if s.isdigit() else string_list).append(s)

print(num_list,string_list)
</code></pre>

<p>result:</p>

<pre><code>['45', '56'] ['hello', 'foo']
</code></pre>

<p>Notes:</p>

<ul>
<li>despite the parenthesized syntax and the context of the question, <code>(num_list if s.isdigit() else string_list)</code> is not a generator, a ternary expression (protected between parentheses to counter <code>.append</code> precedence) which returns <code>num_list</code> if s is a sequence of (positive) digits and <code>string_list</code> if s otherwise.</li>
<li>this code won't work with negative numbers because <code>isdigits</code> will return false. You'll have to code a special function for that (classical problem here on SO)</li>
</ul>

python python-2.7 python-3.x list-comprehension