Update list in-place, converting 'True'/'False' elements to 1/0
<p>In python, supposed I have a list: </p>

<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] 
</code></pre>

<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p>

<pre><code>l = [  1, 0, 'myname', 1, 0, 'foo' ]
</code></pre>

<p>Your problem is similar to <code>switch</code> statement:</p>

<pre><code>switch(ch):
    case "True": 
        return 1
    case "False": 
        return 0
    default: 
        return ch
</code></pre>

<p>But since in Python we do not have switch statement but we can achieve similar functionality by creating the function as:</p>

<pre><code>def check_for_value(value):
    return {'True': 1,
            'False': 0,
           }.get(value, value)
</code></pre>

<p>This function will return <code>0</code> or <code>1</code> based on if the value passed is <code>False</code> or <code>True</code>. Else it will return back the <code>value</code> (similar to <code>default</code> case in <code>switch</code>).</p>

<p>Now you can do list comprehension to achieve what you want:</p>

<pre><code>&gt;&gt;&gt; l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] 
&gt;&gt;&gt; [check_for_value(i) for i in l]
[1, 0, 'myname', 1, 0, 'foo']
</code></pre>

<p>OR, you may use <code>map()</code> instead of list comprehension as:</p>

<pre><code>&gt;&gt;&gt; map(check_for_value, l)
[1, 0, 'myname', 1, 0, 'foo']
</code></pre>

python list dictionary